changeset 252:cf5f8b929da9

text_x_arnica: refactored multiple subarrays into a dict and tuples
author Reimar Bauer <rb.proj AT googlemail DOT com>
date Wed, 10 Sep 2008 10:09:35 +0200
parents 1c73ae375f63
children 902a0b543b9b
files data/plugin/parser/text_x_arnica.py
diffstat 1 files changed, 100 insertions(+), 114 deletions(-) [+]
line wrap: on
line diff
--- a/data/plugin/parser/text_x_arnica.py	Tue Sep 09 11:09:09 2008 +0200
+++ b/data/plugin/parser/text_x_arnica.py	Wed Sep 10 10:09:35 2008 +0200
@@ -36,6 +36,7 @@
 
 parser_name = __name__.split('.')[-1]
 
+
 def arnica_settings(target_page=u'', columns=4, file_regex=u'.',
                     image_for_webnail=False,
                     show_text=True, show_date=True, show_tools=False,
@@ -118,13 +119,7 @@
 
         self.inner_table_style = ' style="border-style:none; margin:10px;"'
         self.td_style = ' align="center" style="padding:0; margin:2px 2px; border-style:none"'
-        self.web_key = [] # array for webnail keys (medium_resolution_image)
-        self.high_resolution_image = [] # array for images
-        self.thumb_key = [] # array for thumbnail keys
-        self.exif_date = [] # array of exif date description
-        self.imgtype = [] # array of imagetype of high_resolution_image image
-        self.description = [] # array of description
-        self.webnail_image = [] # array of images for forms
+        self.arnica_image = {} # self.arnica_image[image] = (webnail, thumbnail, imgtype, exif_date, description, order)
 
     def get_exif_info(self, file_name, key):
         """ gets exif info from image file
@@ -198,12 +193,11 @@
             "this_target": this_target,
         }
 
-    def html_tools(self, idx):
+    def html_tools(self, image):
         """ html code of thumbnails view with contol
         @param idx: index position of corresponding data
         """
 
-        this_image = self.high_resolution_image[idx]
         html = """
 <form action="%(url)s" method="POST" enctype="multipart/form-data">
     <div class="get-image">
@@ -234,18 +228,18 @@
             "tablestyle": self.inner_table_style,
             "style": self.td_style,
             "thumbnail_width": self.thumbnail_width,
-            "description": packLine([self.description[idx]] + self.description),
-            "exif_date": packLine([self.exif_date[idx]] + self.exif_date),
-            "target": self.webnail_image[idx],
-            "original_images": packLine([self.high_resolution_image[idx]] + self.high_resolution_image),
-            "images": packLine([self.webnail_image[idx]] + self.webnail_image),
-            "original_images": packLine([self.high_resolution_image[idx]] + self.high_resolution_image),
-            "this_target": self.high_resolution_image[idx],
-            "html_tools_restricted": self.html_tools_restricted(this_image),
+            "description": packLine([self.arnica_image[image][4]] + [self.arnica_image[img][3] for img in self.arnica_image.keys()]),
+            "exif_date": packLine([self.arnica_image[image][3]] + [self.arnica_image[img][3] for img in self.arnica_image.keys()]),
+            "target": self.arnica_image[image][0],
+            "original_images": packLine([image] + self.arnica_image.keys()),
+            "images": packLine([self.arnica_image[image][0]] + [self.arnica_image[img][0] for img in self.arnica_image.keys()]),
+            "original_images": packLine([image] + self.arnica_image.keys()),
+            "this_target": image,
+            "html_tools_restricted": self.html_tools_restricted(image),
         }
         return html
 
-    def html_show_tools(self, idx):
+    def html_show_tools(self, image):
         """ shows toolbox
         @param idx: index position of corresponding data
         """
@@ -254,10 +248,10 @@
         if self.show_tools:
             html = '<div class="html-show-tools">%(tools)s</div>' % {
                 "style": self.td_style,
-                "tools": self.html_tools(idx)}
+                "tools": self.html_tools(image)}
         return html
 
-    def html_show_date(self, idx):
+    def html_show_date(self, image):
         """ shows date
         @param idx: index position of corresponding data
         """
@@ -265,10 +259,10 @@
         html = ''
         if self.show_date:
             html = '<div class="html-show-date">%(this_exif_date)s</div>' % {
-                "this_exif_date": self.formatter.text(self.exif_date[idx])}
+                "this_exif_date": self.formatter.text(self.arnica_image[image][3])}
         return html
 
-    def html_show_alias(self, idx):
+    def html_show_alias(self, image):
         """ alias text below image
         @param idx: index position of corresponding data
         """
@@ -276,17 +270,17 @@
         html = ''
         if self.show_text:
             html = '<div class="html-show-alias"> %(this_alias)s</div>' % {
-                    "this_alias": self.to_wikitext(self.description[idx])}
+                    "this_alias": self.to_wikitext(self.arnica_image[image][4])}
         return html
 
-    def html_arrange_thumbnails(self, idx):
+    def html_arrange_thumbnails(self, image):
         """ defines arrangement of thumbnail, text, date and tools
         @param idx: index positionn of corresponding data
         """
 
         title = ""
         if self.album:
-            title = '<div class="title">%(n)d images (%(album_title)s)</div>' % {"n": len(self.high_resolution_image),
+            title = '<div class="title">%(n)d images (%(album_title)s)</div>' % {"n": len(self.arnica_image),
                                                         "album_title": self.album_title or self.pagename}
         html = """
 <div class="arrange-thumbnails">
@@ -313,16 +307,16 @@
             "style": self.inner_table_style,
             "url": Page(self.request, self.pagename).url(self.request),
             "pagename": self.pagename,
-            "description": packLine([self.description[idx]] + self.description),
-            "exif_date": packLine([self.exif_date[idx]] + self.exif_date),
-            "target": self.webnail_image[idx],
-            "original_images": packLine([self.high_resolution_image[idx]] + self.high_resolution_image),
-            "images": packLine([self.webnail_image[idx]] + self.webnail_image),
-            "thumbnail": cache.url(self.request, self.thumb_key[idx]),
+            "description": packLine([self.arnica_image[image][4]] + [self.arnica_image[img][4] for img in self.arnica_image.keys()]),
+            "exif_date": packLine([self.arnica_image[image][3]] + [self.arnica_image[img][3] for img in self.arnica_image.keys()]),
+            "target": self.arnica_image[image][0],
+            "original_images": packLine([image] + self.arnica_image.keys()),
+            "images": packLine([self.arnica_image[image][0]] + [self.arnica_image[img][0] for img in self.arnica_image.keys()]),
+            "thumbnail": cache.url(self.request, self.arnica_image[image][1]),
             "thumbnail_width": self.thumbnail_width,
-            "html_tools": self.html_show_tools(idx),
-            "date_html": self.html_show_date(idx),
-            "alias_html": self.html_show_alias(idx),
+            "html_tools": self.html_show_tools(image),
+            "date_html": self.html_show_date(image),
+            "alias_html": self.html_show_alias(image),
         }
         return html
 
@@ -332,30 +326,24 @@
         @param files: file names of images
         @param image_alias: text alias for image file
         """
-
+        order = 0
         for attfile in files:
-            if image_alias.get(attfile):
-                # use alias
-                self.description.append(image_alias.get(attfile)[0])
-            else:
-                # use filename
-                self.description.append(attfile)
-            self.high_resolution_image.append(attfile)
-            fname, ext = os.path.splitext(attfile)
-            key = cache.key(self.request, itemname=self.pagename, attachname=attfile)
-            webnail = 'W_%s_%s' % (self.webnail_width, key)
-            thumbfile = 'T_%s_%s' % (self.thumbnail_width, key)
-            if ext in ('.gif', '.png'):
-                self.imgtype.append('PNG')
-            else:
-                self.imgtype.append("JPEG")
+            if os.path.join(path, attfile):
+                description = attfile
+                if image_alias.get(attfile):
+                    # use alias
+                    description = image_alias.get(attfile)[0]
+                fname, ext = os.path.splitext(attfile)
+                key = cache.key(self.request, itemname=self.pagename, attachname=attfile)
+                webnail = 'W_%s_%s' % (self.webnail_width, key)
+                thumbfile = 'T_%s_%s' % (self.thumbnail_width, key)
+                imgtype = "jpeg"
+                if ext in ('.gif', '.png'):
+                    imgtype = 'png'
 
-            att_file = os.path.join(path, attfile)
-            if os.path.exists(att_file):
-                self.web_key.append(webnail)
-                self.thumb_key.append(thumbfile)
-                date = self.get_exif_info(att_file, key)
-                self.exif_date.append(self.formatter.text(date))
+                exif_date = self.formatter.text(self.get_exif_info(os.path.join(path, attfile), key))
+                self.arnica_image[attfile] = (webnail, thumbfile, imgtype, exif_date, description, str(order))
+                order += 1
 
     def to_wikitext(self, text):
         """ converts text to wiki name if it is written as WikiName or [[wikiname]]
@@ -432,7 +420,7 @@
             self.define_thumb_webnails(path, all_files, image_alias)
         return all_files
 
-    def create_thumbnail_and_webnail_image(self, image, webnail, thumbnail, image_type):
+    def create_thumbnail_and_webnail_image(self):
         """ creates thumbnails and webnails cache files for given image type
         @param image: filename of image
         @param webnail: name of webnail file
@@ -446,33 +434,33 @@
             return
 
         path = AttachFile.getAttachDir(self.request, self.pagename, create=1)
-        imagef = os.path.join(path, image)
-
-        if os.path.getsize(imagef) == 0:
-            return
-
-        if self.renew:
-            cache.remove(self.request, webnail)
-            cache.remove(self.request, thumbnail)
+        for image in self.arnica_image.keys():
+            imagef = os.path.join(path, image)
+            if os.path.getsize(imagef) == 0:
+                continue
 
-        if not cache.exists(self.request, webnail) or not cache.exists(self.request, thumbnail):
-            try:
-                im_obj = Image.open(imagef)
-            except IOError:
-                msg = _("Can not access attachment: %(filename)s. Often the case for this error is an emtpy image attachment.") % {"filename": os.path.basename(imagef)}
-                self.request.write(self.formatter.text(msg))
-                return
-            else:
-                # ToDo may be it is better to just copy the image to the new location
-                # currently PIL does not support exif information
-                if self.image_for_webnail:
-                    buf = StringIO.StringIO()
-                    im_obj.save(buf, image_type)
-                    buf.flush()
-                    buf.seek(0)
-                    cache.put(self.request, webnail, buf, filename=image)
+            if self.renew:
+                cache.remove(self.request, self.arnica_image[image][0])
+                cache.remove(self.request, self.arnica_image[image][1])
+
+            if not cache.exists(self.request, self.arnica_image[image][0]) or not cache.exists(self.request, self.arnica_image[image][1]):
+                try:
+                    im_obj = Image.open(imagef)
+                except IOError:
+                    msg = _("Can not access attachment: %(filename)s. Often the case for this error is an emtpy image attachment.") % {"filename": os.path.basename(imagef)}
+                    self.request.write(self.formatter.text(msg))
+                    continue
+                else:
+                    # ToDo may be it is better to just copy the image to the new location
+                    # currently PIL does not support exif information
+                    if self.image_for_webnail:
+                        buf = StringIO.StringIO()
+                        im_obj.save(buf, self.arnica_image[image][2])
+                        buf.flush()
+                        buf.seek(0)
+                        cache.put(self.request, self.arnica_image[image][0], buf, filename=imagef)
             # XXX later, a unit conversion method for using other units than 'px' is needed
-            if not cache.exists(self.request, webnail):
+            if not cache.exists(self.request, self.arnica_image[image][0]):
                 try:
                     exif = im_obj._getexif()
                 except (AttributeError, KeyError):
@@ -499,23 +487,23 @@
                         pass
 
                 buf = StringIO.StringIO()
-                im_obj.save(buf, image_type)
+                im_obj.save(buf, self.arnica_image[image][2])
                 buf.flush()
                 buf.seek(0)
-                cache.put(self.request, webnail, buf, filename=image)
+                cache.put(self.request, self.arnica_image[image][0], buf, filename=image)
                 buf.close()
 
-            if not cache.exists(self.request, thumbnail):
+            if not cache.exists(self.request, self.arnica_image[image][1]):
                 try:
                     im_obj.thumbnail((int(self.thumbnail_width.strip('px')), int(self.thumbnail_width.strip('px'))), Image.ANTIALIAS)
                 except IOError:
                     # one reason can be that the image file is truncated
                     return
                 buf = StringIO.StringIO()
-                im_obj.save(buf, image_type)
+                im_obj.save(buf, self.arnica_image[image][2])
                 buf.flush()
                 buf.seek(0)
-                cache.put(self.request, thumbnail, buf, filename=image)
+                cache.put(self.request, self.arnica_image[image][1], buf, filename=image)
                 buf.close()
 
     def render(self, formatter):
@@ -546,7 +534,7 @@
             self.request.write(self.formatter.text(text))
             self.request.write(self.formatter.div(1))
             self.request.write(self.formatter.preformatted(1))
-            for image in self.high_resolution_image:
+            for image in self.arnica_image.keys():
                 text = ' * [[%(image)s|alias]]\n' % {
                            'image': image,
                         }
@@ -555,7 +543,8 @@
             self.request.write(self.formatter.div(0))
             self.request.write(self.formatter.div(0))
 
-        cols = min([self.columns, len(self.high_resolution_image)])
+        self.create_thumbnail_and_webnail_image()
+        cols = min([self.columns, len(self.arnica_image)])
         if self.album:
             cols = 1
         data = TupleDataset()
@@ -564,14 +553,25 @@
             data.columns.extend([Column('', label=(''))])
         col_count = 1
         result = []
-        for image in self.high_resolution_image:
-            # ToDo use a longer var
-            i = self.high_resolution_image.index(image)
-            self.create_thumbnail_and_webnail_image(image, self.web_key[i],
-                                                    self.thumb_key[i], self.imgtype[i])
-            if not self.album:
-                self.webnail_image = self.web_key
-                text = self.html_arrange_thumbnails(i)
+
+        if self.album:
+            album_image = self.album_image or self.arnica_image.keys()[0] #self.high_resolution_image[0]
+            if not album_image in self.arnica_image.keys():
+                    text = self.formatter.text(_("""You can't use as album image:
+"%(album_image)s" because it does not exist or it is not listed
+in your item list!""") % {"album_image": album_image, })
+            else:
+                #self.create_thumbnail_and_webnail_image(image, self.web_key[i], self.thumb_key[i], self.imgtype[i])
+                #self.webnail_image = self.web_key
+                text = self.html_arrange_thumbnails(album_image)
+
+            result.append(''.join(text))
+        else:
+            image_names = self.arnica_image.keys()
+            index = [self.arnica_image[img][5] for img in image_names]
+            selected_images = [image_names[int(idx)] for idx in index]
+            for image in selected_images:
+                text = self.html_arrange_thumbnails(image)
                 if col_count <= cols:
                     result.append(''.join(text))
                 if col_count == cols:
@@ -580,24 +580,10 @@
                     # resets the result list after the row is added
                     result = []
                 col_count += 1
-        if result and not self.album:
-            # ToDo use a longer var
-            for i in range(cols - col_count + 1):
-                result.append('')
-        if self.album:
-            album_image = self.album_image or self.high_resolution_image[0]
-            try:
+            if result:
                 # ToDo use a longer var
-                i = self.high_resolution_image.index(album_image)
-                self.create_thumbnail_and_webnail_image(image, self.web_key[i], self.thumb_key[i], self.imgtype[i])
-                self.webnail_image = self.web_key
-                text = self.html_arrange_thumbnails(i)
-            except ValueError:
-                text = self.formatter.text(_("""You can't use as album image:
-"%(album_image)s" because it does not exist or it is not listed
-in your item list!""") % {"album_image": album_image, })
-
-            result.append(''.join(text))
+                for i in range(cols - col_count + 1):
+                    result.append('')
 
         # adds the last row if it is not filled up
         if result: