python-fu-dump / dump.py

  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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
from gimpfu import *
from string import Template
from datetime import datetime
from collections import *
import gtk
import os
import ctypes
import unicodedata
import re
from pprint import pprint, pformat

PROC_CSS = """html, body
{
        width:100%;
        height:100%;
        margin:0px;
}

body
{
        width:578px;
        max-width:578px;
        margin:24px auto 0px 36px;
}

p, table
{
        margin:0px 0px 0px 12px;
}

nav
{
        display:block;
        margin-bottom:6px;
        text-align:center;
}

h1
{
        margin-top:0px;
}

h1, h4
{
        margin-bottom:0px;
}

div#author
{
        text-align:right;
        font-style:italic;
}

span.date
{
        font:bold 14px Monospace,small-caps;
}

table
{
        font-family:'Trebuchet MS', Arial, Helvetica, sans-serif;
        width:100%;
        border-collapse:collapse;
}

table td, table th 
{
        font-size:1em;
        border:1px solid SlateGray;
        padding:3px 7px 2px 7px;
}

table th
{
        font-size:1.1em;
        text-align:left;
        padding-top:5px;
        padding-bottom:4px;
        background-color:LightSlateGray;
        color:#ffffff;
}

table tr.alt td 
{
        color:#000000;
        background-color:#C9CFD6;
}
"""
PROC_HTML = """<!DOCTYPE html>
<html>
        <head>
                <title>pdb: ${proc_name}</title>

                <meta name="description" content="${proc_blurb}">
                <meta name="author" content="Code Fox">
                <meta charset="UTF-8">

                <link rel="stylesheet" type="text/css" href="proc.css">
        </head>
        <body>
                <nav>
                        <a href="${prev_link}" style="float:left;">previous</a>
                        <a href="${index_link}">index</a>
                        <a href="${next_link}" style="float:right;">next</a>
                </nav>
                <hr style="margin-bottom:0px;"/>
                <div style="display:inline-block;">
                        <h1>
                                ${proc_name}
                        </h1>
                        <div id="author">
                                ${proc_author}
                        </div>
                </div>
                <hr style="margin-bottom:0px;"/>
                <p id="copyright" style="margin:0">
                        <span class="date">${proc_date}</span><br>
                        ${proc_copyright}
                </p>
                <h4>Description</h4>
                <p id="description">
                        ${proc_blurb}
                </p>
                <h4>Help</h4>
                <p id="help">
                        ${proc_help}
                </p>
                <hr />
                <h4>Type</h4>
                <p id="type">
                        ${proc_type}
                </p>
                <h4>Parameters</h4>
                ${parameters}
                <h4>Return</h4>
                ${results}
                <hr style="margin-bottom:0px;" />
                <nav>
                        <a href="${prev_link}" style="float:left;">previous</a>
                        <a href="${index_link}">index</a>
                        <a href="${next_link}" style="float:right;">next</a>
                </nav>
        </body>
</html>
"""
TABLE_HTML = """
                <table>
                        <thead>
                                <tr>
                                        <th>Type</th>
                                        <th>Name</th>
                                        <th>Description</th>
                                </tr>
                        </thead>
                        <tbody>
                                ${body}
                        </tbody>
                </table>
"""
TR_HTML = """
                                <tr ${class}>
                                        <td>
                                                ${type}
                                        </td>
                                        <td>
                                                ${name}
                                        </td>
                                        <td>
                                                ${desc}
                                        </td>
                                </tr>

"""
INDEX_TEMPLATE = """<!DOCTYPE html>
<html>
        <head>
                <title>pdb: index</title>

                <meta name="description" content="">
                <meta name="author" content="Code Fox">
                <meta charset="UTF-8">

                <link rel="stylesheet" type="text/css" href="main.css">

                </style>
        </head>
        <body>
                <a id="top"></a>
                <div style="text-align:center">
                        <div style="display:inline-block; margin:0px auto 0px auto;">
                                <h1>Gimp Plugin Database</h1>
                                <div id="author">
                                        <span class="date">
                                                ${date}
                                        </span>
                                </div>
                        </div>
                </div>
                ${body}
        </body>
</html>
"""

MessageBox = ctypes.windll.user32.MessageBoxA

def escape_html(html):
        """
        Returns the given HTML with ampersands, quotes and angle brackets encoded.
        """
        html = unicode(html)
        html = html.replace('&', '&amp;')
        html = html.replace('<', '&lt;')
        html = html.replace('>', '&gt;')
        html = html.replace('"', '&quot;')
        html = html.replace("'", '&#39;')

        return html.encode('ascii', 'ignore')

def slugify(value):
        """
        Normalizes string, converts to lowercase, removes non-alpha characters,
        and converts spaces to hyphens.

        Based on code in: Django
        """
        value = unicodedata.normalize('NFKD', unicode(value))
        value = value.encode('ascii', 'ignore')
        value = re.sub('[^\w\s-]', '', value).strip().lower()
        value = re.sub('[-\s]+', '-', value)
        return value

def get_dir() :
        response = ""

        # Check for new pygtk: this is new class in PyGtk 2.4
        if (gtk.pygtk_version < (2,3,90)) :
                MessageBox(None, "This plugin requires PyGtk 2.3.90 or later", "Error", 0)
                return response

        dialog = gtk.FileChooserDialog(
                "Dump to...",
                None,
                gtk.FILE_CHOOSER_ACTION_OPEN,
                (
                        gtk.STOCK_CANCEL,
                        gtk.RESPONSE_CANCEL,
                        gtk.STOCK_OPEN,
                        gtk.RESPONSE_OK
                )
        )
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)

        if (dialog.run() == gtk.RESPONSE_OK) :
                response = dialog.get_filename()
        dialog.destroy()

        return response

def prepare(root) :
        # create sub directory if it doesnt exist
        outDirectory = os.path.join(
                        root,
                        "pdb"
        )

        if not os.path.exists(outDirectory):
                os.makedirs(outDirectory)

        with open(os.path.join(root, "main.css"),'w') as f:
                f.write(PROC_CSS)

        return None


def var_type(t) :
        """
        in the documentation, but not defined in gimpfu
        PF_REGION:"PF_REGION"
        """
        if (t not in {PF_INT8:"PF_INT8",PF_INT16:"PF_INT16",PF_INT32:"PF_INT32",PF_INT:"PF_INT",PF_FLOAT:"PF_FLOAT",PF_STRING:"PF_STRING",PF_VALUE:"PF_VALUE",PF_COLOR:"PF_COLOR",PF_COLOUR:"PF_COLOUR",PF_IMAGE:"PF_IMAGE",PF_LAYER:"PF_LAYER",PF_CHANNEL:"PF_CHANNEL",PF_DRAWABLE:"PF_DRAWABLE",PF_TOGGLE:"PF_TOGGLE",PF_BOOL:"PF_BOOL",PF_RADIO:"PF_RADIO",PF_SLIDER:"PF_SLIDER",PF_SPINNER:"PF_SPINNER",PF_ADJUSTMENT:"PF_ADJUSTMENT",PF_FONT:"PF_FONT",PF_FILE:"PF_FILE",PF_BRUSH:"PF_BRUSH",PF_PATTERN:"PF_PATTERN",PF_GRADIENT:"PF_GRADIENT",PF_PALETTE:"PF_PALETTE"}) :
                return "unknown"

        return VAR_TYPES[t]

def proc_type(t) :
        if (t not in {PLUGIN:"PROC_PLUG_IN",EXTENSION:"PROC_EXTENSION",TEMPORARY:"PROC_TEMPORARY"}) :
                return "unknown"

        return PROC_TYPES[t]

def table(lst) :
        row = dict()
        html = ""
        alt = False
        for item in lst :
                row["class"] = ""
                if (True == alt) :
                        row["class"] = ' class="alt"'
                row["type"] = dump_var_type(item[0])
                row["name"] = escape(item[1])
                row["desc"] = escape(item[2])

                html += Template(TR_HTML).safe_substitute(row)
                alt = not alt

        return Template(TABLE_HTML).safe_substitute({"body":html})

def file_name(name) :
        return "%s.html"%(slugify(name))

def plain_table(heading, lst, max_row_length=5):
        buf = ""
        buf += Template('\t\t<a id="${heading}"><h4>${heading}</h4></a>\n').safe_substitute({"heading":heading})
        buf += '\t\t<table>\n\t\t\t<tr>\n'
        count = 0
        for item in lst:
                count += 1
                # special
                buf += Template('\t\t\t\t<td><a href="pdb/${file}.html" title="${item}">${item}</a></td>\n').safe_substitute({"file":file_name(item), "item":item})
                # special
                if 0 == (count % max_row_length):
                        buf += '\t\t\t</tr>\n\t\t\t<tr>\n'

        buf += '\t\t\t</tr>\n\t\t</table>\n\t\t<nav><a href="#top">top</a></nav>\n'

        if (0 == count) :
                return ""

        return buf

def insert(root, path):

        for part in path:
                ptr = None
                for tup in root[1]:
                        if (tup[0] == part):
                                ptr = tup
                                break

                if None == ptr:
                        ptr = (part, list())
                        root[1].append(ptr)
                        root[1].sort(key=lambda tup: tup[0])

                root = ptr

def size(root):

        children = 0
        unvisited = deque()
        unvisited.append(root)

        while 0 != len(unvisited):
                node = unvisited.popleft()
                children += 1
                for tup in node[1]:
                        unvisited.append(tup)

        return children

def namespaces(root, delimiter="-", minSize=10):

        ns_list = list()
        unvisited = list()
        visited = dict()

        unvisited.append(root)

        while 0 != len(unvisited):

                node = unvisited[-1]
                namespace = delimiter.join(map(lambda tup: tup[0], unvisited))

                for child in node[1]:
                        childspace = namespace + delimiter + child[0]
                        if(childspace not in visited):
                                visited[childspace] = True
                                unvisited.append(child)
                                break

                if(node == unvisited[-1]):
                        # post fix; no new unvisited children found
                        if(size(node) > minSize):
                                ns_list.append(namespace)
                        elif (node == root):
                                ns_list.append(namespace)

                        unvisited.pop()

        return ns_list

def headings(procs, delimiter="-", minSize=10):

        root = ("root", list())

        for proc in procs:
                insert(root, proc.split(delimiter))

        heading_list = list()
        for node in root[1]:
                heading_list.extend(namespaces(node, delimiter, minSize))

        return map(lambda s: s + delimiter,heading_list)

def index(procs) :

        lst = headings(procs)

        buf = '\t\t<hr>\n\t\t<nav class="main">'
        for heading in lst :
                buf += Template('<a href="#${heading}-" style="font-size:1.05em;">${heading}</a>').safe_substitute({"heading":heading[:-1]})

                if(heading != lst[-1]):
                        buf += " &bull; "

        buf += "</nav>\n\t\t<hr>\n"

        for heading in lst :
                buf += plain_table(heading, filter(lambda name: name.startswith(heading),procs))
                procs = filter(lambda name: not name.startswith(heading),procs)

        return buf

def dump_pdb() :

        root = get_dir()
        if("" == root) :
                return None

        prepare(root)

        # loop through PDB
        procs = gimp.pdb.query()
        procs.sort()

        with open(os.path.join(root,"index.html"), "w+") as f :
                f.write(Template(INDEX_TEMPLATE).safe_substitute({"date":datetime.now().strftime("%A, %d. %B %Y %I:%M%p"),"body":index(procs)}))

        return None

register(
        #name
        "dump-pdb",
        #blurb
        "dumps pdb database to HTML",
        #help
        "man up buttercup",
        #author
        "codefox",
        #copyright
        "MIT license => rtfm",
        #date
        "Jan 29, 2013",
        #menu path
        "<Toolbox>/Help/Procedure Dump",
        #image types
        None,
        #params
        [],
        #results
        [],
        #function
        dump_pdb
)

main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.