def postprocess(opts, config):
    """
    tkgen によるコード変換が全て終えられた後に実行される後処理
    変換後のファイルおよびファイルツリー全体に対して行いたい処理をここに追記してね

    @param opts  : 起動引数 (optparse.OptionParser のパース結果)
    @param config: コンフィグファイルの内容 (tkgen.tkutil.Config のオブジェクト)
    """

    #cprint("<yellow:* run make_preview/>")
    #make_preview.doit(config)

    cprint("\n<yellow:* run make_index/>")
    make_index.doit(config)

    cprint("\n<yellow:* run replace_home_path/>")
    replace_home_path.doit(config)
def doit(config):
    """
    自分が置かれている階層の深さを見て、
    html 内の $HOME を、そこがルートディレクトリになるように置き換える。

    例えば build/dir1/dir2/hoge.html 内に
    '$HOME/resource/fuga.png'    と書かれていたとしたら、
    '../../../resource/fuga.png' となるように置換する
    """

    REPLACE_TAG = '$HOME'
    for path in get_all_files(config.path.build, '*.html'):
        print ' '*4, path
        result_lines = []
        tag_count = 0
        dir_level = path.count('/')
        dest_path = '..' + ('/..' * (dir_level - 1))

        # read file
        in_file = open(path, 'r')
        try:
            for i, line in enumerate(in_file):
                tag_count += line.count(REPLACE_TAG)
                replaced_line = line.replace(REPLACE_TAG, dest_path)
                result_lines.append(replaced_line)
        finally:
            in_file.close()

        # write file
        out_file = open(path, 'w')
        try:
            out_file.writelines(result_lines)
        finally:
            out_file.close()

        if tag_count > 0:
            cprint("<green:%s %d %s/>" % (' '*8, tag_count, '$HOME replaced'))
        else:
            cprint("<red:%s *** $HOME not found ***/>" % (' '*8))
def doit(config):
    """
    ページ内に PREVIEW_[リンク先] の形式の id があれば、
    そのエレメントのマウスオーバ時に「次のページのプレビュー内容」のテキストを
    id = "PREVIEW_AREA" のエレメントに表示する。
    そのための JS のコードは FOOTER_JS_AREA の位置に埋め込まれる
    """

    PREVIEW_ID_SEARCH_PATTERN = 'id="_PREVIEW_'
    PREVIEW_ID_TAG_PATTERN    = '_PREVIEW_(.*)"'
    PREVIEW_ID_TAG_PREFIX     = '_PREVIEW_'
    PREVIEW_AREA_TAG = 'PREVIEW_AREA'
    INSERT_JS_TAG    = 'FOOTER_JS_AREA'

    for path in get_all_files(config.path.build, '*.html'):
        print ' '*4, path
        result_lines = []
        preview_ids  = []
        footer_js_line_num = 0

        # read file
        in_file = open(path, 'r')
        try:
            for i, line in enumerate(in_file):
                result_lines.append(line)
                if re.search(PREVIEW_ID_SEARCH_PATTERN, line):
                    groups = re.search(PREVIEW_ID_TAG_PATTERN, line).groups()
                    href   = groups[0]
                    preview_id = PREVIEW_ID_TAG_PREFIX + href
                    preview_ids.append({
                        'id'  : preview_id,
                        'href': href.replace('--', '/') + '.html'
                    })

                if re.search(INSERT_JS_TAG, line):
                    footer_js_line_num = i
        finally:
            in_file.close()
        if not preview_ids:
            cprint("<red:%s *** not found ***/>" % (' '*8))
            continue

        # make preview index and embed it in html as JavaScript
        js_code = '\n'
        js_code += '    if (!tk) { tk = {}; }\n'
        js_code += '    tk.PREVIEW_DATA = {};\n'
        for preview_data in preview_ids:
            preview_text = get_preview_text(path, preview_data['href'])
            js_code += '    tk.PREVIEW_DATA["%s"] = "%s";\n' % (preview_data['id'], preview_text)

        # insert event attachment code as JavaScript
        for i, preview_data in enumerate(preview_ids):
            js_code += '    $("#%s").mouseover(function() {\n' % (preview_data['id'])
            js_code += '        $("#%s").html(tk.PREVIEW_DATA["%s"]);\n' % (PREVIEW_AREA_TAG, preview_data['id'])
            #js_code += '        $("#%s").fadeIn(500);\n' % (PREVIEW_AREA_TAG);
            js_code += '        $(".auto_preview").css("margin-top", "%dem");\n' % (i * 4)
            js_code += '        $(".auto_preview").css("color", "#eee");\n'
            js_code += '        $(".auto_preview").animate(\n'
            js_code += '            {"color": "#333"}, 300\n'
            js_code += '        );\n'
            js_code += '    });\n'

        result_lines[footer_js_line_num] += js_code

        # write file
        out_file = open(path, 'w')
        try:
            out_file.writelines(result_lines)
        finally:
            out_file.close()

        cprint("<green:%s %d %s/>" % (' '*8, len(preview_ids), 'preview links found'))
def doit(config):
    """
    ページ内の h タグをさらってインデックスをつくり、
    タグの位置に挿入する。
    また、ディレクトリ位置を観てページのパンくずリストも挿入する。
    タグが見つからなければ何もしない
    """

    BREADCRUMBS_TAG = 'POST_PROCESS_BREADCRUMBS'
    INDEX_TAG       = 'POST_PROCESS_GLOBAL_INDEX'
    for path in get_all_files(config.path.build, '*.html'):
        print ' '*4, path
        result_lines = []
        head_items   = []
        insert_line_num      = None
        breadcrumbs_line_num = None

        # read file
        in_file = open(path, 'r')
        try:
            for i, line in enumerate(in_file):
                result_lines.append(line)
                if insert_line_num == None and re.search(INDEX_TAG, line):
                    insert_line_num = i
                if breadcrumbs_line_num == None and re.search(BREADCRUMBS_TAG, line):
                    breadcrumbs_line_num = i

                header_pattern = '<h(\d)(.*)>(.*)</h\d>'
                if re.search(header_pattern, line):
                    groups = re.search(header_pattern, line).groups()
                    header_level = groups[0]
                    header_class = groups[1]
                    header_title = groups[2]
                    head_items.append((i, header_level, header_class, header_title))
        finally:
            in_file.close()
        if insert_line_num == None:
            cprint("<red:%s *** not found ***/>" % (' '*8))
            continue

        # make breadcrubms list and insert it
        breadcrumbs_lines = get_breadcumbs(path)
        result_lines[breadcrumbs_line_num] = breadcrumbs_lines

        # make index and insert it
        index_lines = '<ul class="global_index">\n'
        for i, head in enumerate(head_items):
            (line_num, lv, class_name, title) = head
            numbering = i + 1
            # insert anchor
            result_lines[line_num] = re.sub(
                '<h\d.*/h\d>',
                '<h%s%s id="head%d">%s</h%s>' % (lv, class_name, numbering, title, lv),
                result_lines[line_num]
            )

            # generate link
            index_lines += '    <li class="level%s" id="li_index%s"><a href="#head%d">%s</a></li>\n' \
                % (lv, numbering, numbering, title)
        index_lines += '</ul>'
        result_lines[insert_line_num] = index_lines

        # write file
        out_file = open(path, 'w')
        try:
            out_file.writelines(result_lines)
        finally:
            out_file.close()

        cprint("<green:%s %d %s/>" % (' '*8, len(head_items), 'headers found'))