~flimm/ooo-thumbnailer/releases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python2.6
# Copyright 2010 David D Lowe <daviddlowe.flimm@gmail.com>
#      
# 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 Street, Fifth Floor, Boston,
# MA 02110-1301, USA.


import subprocess
import os, sys
import gtk
import gtk.gdk
import gobject
import glob
import multiprocessing
import threading
gtk.gdk.threads_init()
gobject.threads_init()


class Application(object):
    def __init__(self):
        window = gtk.Window()
        window.connect("destroy", self.quit)
        
        vbox = gtk.VBox(False, 2)
        window.add(vbox)
        
        button = gtk.Button("Run tests")
        button.connect("clicked", self.button_callback)
        vbox.pack_start(button, False, False)
        
        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        window.add(scrolled)
        
        files = self.list_of_files()
        
        self.box = gtk.Table(len(files), 2)
        
        headings = ("Filename", "Size", "Time spent", "Outcome")
        for ii, heading in enumerate(headings):
            label = gtk.Label()
            label.set_markup("<b>%s</b>" % heading)
            self.box.attach(label, ii, ii + 1, 0, 1)
        
        self.labels = {}
        for y, file in enumerate(files):
            label = gtk.Label(file.split("/")[-1])
            label.set_alignment(0, 0.5)
            self.labels[file] = [label, 
                gtk.Label(self.size_string(os.path.getsize(file))),
                gtk.Label("."), gtk.Label(".")]
            for x, widget in enumerate(self.labels[file]):
                self.box.attach(widget, x, x + 1, y + 1, y + 2) 

        scrolled.add_with_viewport(self.box)
        
        vbox.pack_start(scrolled)
        
        self.pipe, child_pipe = multiprocessing.Pipe()
        self.process = TimeProcesses(files, child_pipe)
        self.thread = threading.Thread(target=self.monitor_progress)
        
        window.resize(600, 700)
        window.show_all()
    
    def run(self):
        gtk.main()

    @staticmethod
    def list_of_files():
        files = []
        for pattern in ("*.doc", "*.docx", "*.ppt", "*.pptx", "*.xls", "*.xlsx",
        "*.sxc", "*.ods", "*.sxi", "*.sti", "*.odp", "*.otp", "*.sxw",
        "*.stw", "*.odt", "*.odm", "*.ott", "*.stc", "*.ots", "*.sxg", 
        "*.sxd", "*.std", "*.odg", "*.otg", "*.odf", "*.sxm"):
            files.extend(glob.glob(os.path.join(os.path.dirname(__file__),"files/" + pattern)))
        files.sort()
        files = [os.path.abspath(f) for f in files]
        return files
    
    @staticmethod
    def size_string(size):
        for unit in ("B", "kB", "MB", "GB"):
            if size < 1000:
                return str(size) + unit
            size = int(size / 1000)
        return str(size) + "GB"
        
    def monitor_progress(self):
        self.do_monitor_progress = True
        while self.do_monitor_progress:
            if self.pipe.poll(0.2):
                recv = self.pipe.recv()
                if recv[0] == "start":
                    gobject.idle_add(lambda recv=recv: self.modify_label(recv[1], ["<span color=\"red\">...</span>"] * 2))
                elif recv[0] == "complete":
                    print recv[1], recv[2], recv[3].replace("<span color=\"red\">","").replace("</span>","")
                    gobject.idle_add(lambda recv=recv: self.modify_label(recv[1], recv[2:4]))
                elif recv[0] == "quit":
                    print "Done."
                    self.do_monitor_progress = False
                    break
            if not self.process.is_alive():
                break

    def modify_label(self, file, markup_list):
        labels = self.labels[file]
        for ii, markup in enumerate(markup_list):
            if markup:
                labels[ii + 2].set_markup(markup)

    def quit(self, widg):
        if not self.process is None:
            try:
                if self.process.is_alive():
                    self.process.terminate()
            except Exception, ee:
                print >> sys.stderr, str(ee)
        self.do_monitor_progress = False
        gtk.main_quit()
        sys.exit()
   
    def button_callback(self, widget):
        widget.set_sensitive(False)
        self.process.start()
        self.thread.start()

class TimeProcesses(multiprocessing.Process):
    def __init__(self, files, pipe):
        multiprocessing.Process.__init__(self)
        self.files = files
        self.pipe = pipe
        self.script = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            "ooo-thumbnailer")
		
    def run(self):
        if not os.path.isdir(os.path.join(os.path.dirname(self.script), "test/output")):
            os.mkdir(os.path.join(os.path.dirname(self.script), "test/output"))
        for file in self.files:
            if os.path.exists(os.path.join(os.path.dirname(self.script),"test/output/",file.split("/")[-1] + ".png")):
                os.remove(os.path.join(os.path.dirname(self.script), "test/output/", file.split("/")[-1] + ".png"))
        for ii, file in enumerate(self.files):
            self.pipe.send(["start", file])
            time, outcome = self.test_file(file, None)
            self.pipe.send(["complete", file, time, outcome])
        self.pipe.send(["quit"])
			
    def test_file(self, file, label):
        env = os.environ
        env["OVERRIDE_OOOTHUMBNAILER_UNOCONV_MAX_SIZE"] = "-1"
        env["OVERRIDE_OOOTHUMBNAILER_TIMEOUT"] = "-1"
        process = subprocess.Popen(
            ["/usr/bin/time","-f", "_%e_%x_", self.script, 
            file, "test/output/%s.png" % file.split("/")[-1], "128"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            cwd=os.path.dirname(self.script),
            env=env)
        process.wait()
        for line in reversed(process.stderr.readlines()):
            if len(line) > 2 and line[0] == "_" and line[-2] == "_":
                params = line.split("_")
                if int(params[2]) == 0 and \
                os.path.exists(os.path.join(os.path.dirname(self.script), "test/output/%s.png" % file.split("/")[-1])):
                    outcome = "Success"
                elif int(params[2]) == 0:
                    outcome = "<span color=\"red\">Thumbnail not found</span>"
                else:
                    outcome = "<span color=\"red\">Failed (code:%s)</span>" % params[2]
                return params[1] + " seconds", outcome
        return "<span color=\"red\">Python logic error</span>", "<span color=\"red\">Python logic error</span>"

def main():
    Application().run()

if __name__ == "__main__":
    main()