--- DiaView.py	2008-02-15 14:06:27.000000000 -0500
+++ DiaViewMod.py	2008-02-15 13:57:16.000000000 -0500
@@ -9,9 +9,48 @@
 from trac.wiki.macros import ImageMacro
 from trac.util.html import escape, html, Markup
 
+
 class DiaViewMacro(WikiMacroBase):
+    def insert_attachment(self, att_path):
+        """att_path MUST exist in the filesystem"""
+        att_fn = att_path[att_path.rfind("/")+1:] #get filename without path
+        from trac.attachment import Attachment
+        try:
+            attachment = Attachment(self.env, self.module, self.id, att_fn)
+        except Exception:
+            db = self.env.get_db_cnx()
+            handle_ta = True
+            size = 0
+            time = 0
+            cursor = db.cursor()
+            cursor.execute("INSERT INTO attachment "
+                         "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
+                         (self.module, self.id, att_fn,
+                          size, time, 'PNG render of a DIA file', self.req.remote_user,
+                          self.req.remote_addr))
+            if handle_ta:
+                db.commit()
+            attachment = Attachment(self.env, "wiki", self.id, att_fn)
+        url = attachment.href(self.req)
+        att_url = attachment.href(self.req, format='raw')
+        return attachment
+
+    def dia2png(self, dia_path, png_path):
+        try:
+            diacmd = 'dia -l --filter=png --export='+png_path+' '+dia_path
+            self.env.log.info('Running Dia : %s',diacmd)
+            f = popen2.Popen4(diacmd)
+            lines = []
+            while (f.poll() == -1):
+                lines += f.fromchild.readlines()
+                f.wait()      
+            self.env.log.info('Exiting Dia')
+        except Exception, e:
+            self.env.log.info('Dia failed with exception= %s',e)
+            raise Exception('Dia execution failed.')
 
     def render_macro(self, req, name, content):
+        self.req = req
         # args will be null if the macro is called without parenthesis.
         if not content:
             return ''
@@ -52,7 +91,6 @@
                     style['border'] = ' %dpx solid' % int(val);
                 else:
                     attr[str(key)] = val # will be used as a __call__ keyword
-
         # parse filespec argument to get module and id if contained.
         parts = filespec.split(':')
         url = None
@@ -69,12 +107,28 @@
             except Exception:
                 browser_links = []
             if parts[0] in browser_links:   # source:path
-                module, file = parts
+                url = parts[1]
+                self.module = "wiki"
+                self.id = ".diaview"
                 rev = None
-                if '@' in file:
-                    file, rev = file.split('@')
-                url = req.href.browser(file, rev=rev)
-                raw_url = req.href.browser(file, rev=rev, format='raw')
+                if '@' in url:
+                    url, rev = url.split('@')
+                repo = self.env.get_repository(req.authname)
+                node = repo.get_node(url, rev)
+                dia_filename = url[url.rfind("/")+1:]
+                dia_path = "/tmp/lalala.dia" #TODO FIXME choose a proper temp file name and delete it afterwards
+                dia_file = open(dia_path, "w")
+                dia_file.write(node.get_content().read())
+                dia_file.close()
+                attach_base_path = self.env.path + "/attachments/" + self.module + "/" + self.id + "/"
+                #check dir existence
+                import os
+                if not os.path.isdir(attach_base_path):
+                    os.makedirs(attach_base_path)
+                png_fn = attach_base_path + dia_filename.replace(".dia", ".png")
+                self.dia2png(dia_path, png_fn)
+                attachment = self.insert_attachment(png_fn)
+                img_url = attachment.href(req, format='raw')
                 desc = filespec
             else: # #ticket:attachment or WikiPage:attachment
                 # FIXME: do something generic about shorthand forms...
@@ -90,9 +144,6 @@
                 else:
                     module = 'wiki'
         elif len(parts) == 1:               # attachment
-            # determine current object
-            # FIXME: should be retrieved from the formatter...
-            # ...and the formatter should be provided to the macro
             file = filespec
             module, id = 'wiki', 'WikiStart'
             path_info = req.path_info.split('/',2)
@@ -108,65 +159,43 @@
             from trac.attachment import Attachment
             attachment = Attachment(self.env, module, id, file)
             url = attachment.href(req)
-
             dia_url = attachment.href(req, format='raw')
-	    dia_path = attachment.path
-	    dia_filename = attachment.filename
+            dia_path = attachment.path
+            dia_filename = attachment.filename
             img_url = dia_url.replace(".dia",".png")
-	    img_path = dia_path.replace('.dia','.png')
-	    img_filename = dia_filename.replace('.dia','.png')
-
+            img_path = dia_path.replace('.dia','.png')
+            img_filename = dia_filename.replace('.dia','.png')
             self.env.log.info('Getting file modification times.')
-            #get file modification times
             try:
-              dia_mtime = os.path.getmtime(dia_path)
+                dia_mtime = os.path.getmtime(dia_path)
             except Exception:
-              raise Exception('File does not exist: %s', dia_path)
-
+                raise Exception('File does not exist: %s', dia_path)
             try:
-              img_mtime = os.path.getmtime(img_path)
+                img_mtime = os.path.getmtime(img_path)
             except Exception:
-              img_mtime = 0
-                
+                img_mtime = 0
             self.env.log.info('Comparing dia and png file modification times : %s, %s',dia_mtime,img_mtime)
-
-            # if diagram is newer than image, then regenerate image
             if (dia_mtime > img_mtime):
-              try:
-		# TODO: read this comment and adjust the command line to taste
-		# You should probably use the correct path
-		# The options are correct for the 0.96.1, but you may bee to adjust them
-                diacmd = 'dia -l --filter=png --export='+img_path+' '+dia_path
-                self.env.log.info('Running Dia : %s',diacmd)
-	        f = popen2.Popen4(diacmd)
-                lines = []
-                while (f.poll() == -1):
-                  lines += f.fromchild.readlines()
-                  f.wait()	
-	        #ecode = os.spawnl(os.P_WAIT,'/usr/bin/dia','/usr/bin/dia','-l','--export-to-format=png', '--export='+img_path, dia_path)
-                self.env.log.info('Exiting Dia')
-              except Exception, e:
-                self.env.log.info('Dia failed with exception= %s',e)
-                raise Exception('Dia execution failed.')
+                self.dia2png(dia_path, img_path)
             try:
-	      attachment._fetch(img_filename)
-	    except Exception:
-              db = self.env.get_db_cnx()
-              handle_ta = True
-              attachment.size = 0
-              attachment.time = 0
-              cursor = db.cursor()
-              cursor.execute("INSERT INTO attachment "
+                attachment._fetch(img_filename)
+            except Exception:
+                db = self.env.get_db_cnx()
+                handle_ta = True
+                attachment.size = 0
+                attachment.time = 0
+                cursor = db.cursor()
+                cursor.execute("INSERT INTO attachment "
                              "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                              (attachment.parent_type, attachment.parent_id, img_filename,
                               attachment.size, attachment.time, 'PNG render of a DIA file', attachment.author,
                               attachment.ipnr))
-              attachment.filename = img_filename
+                attachment.filename = img_filename
 
-              self.env.log.info('New attachment: %s', img_filename)
+                self.env.log.info('New attachment: %s', img_filename)
 
-              if handle_ta:
-                  db.commit()
+                if handle_ta:
+                    db.commit()
 
             desc = 'JPG render of a DIA file.'
         for key in ['title', 'alt']:
@@ -176,6 +205,4 @@
             attr['style'] = '; '.join(['%s:%s' % (k, escape(v))
                                        for k, v in style.iteritems()])
         result = Markup(html.IMG(src=img_url, **attr)).sanitize()
-        #if not nolink:
-        #    result = html.A(result, href=url, style='padding:0; border:none')
         return result
