#!/usr/bin/env python3
# -*- coding: utf-8 -*-
encoding='utf-8'

#需求：因为keil中把含有带0xFD编码的汉字跳过而造成各种显示乱码的问题，需要在这些汉字后面另加一个“\xfd”
#功能：检索本程序所在目录及所有下级目录中的.c和.h文件，给需要的汉字加“\xfd”
#另：按说Keil 项目路径名的字符中也不能含有带 0xFD 编码的汉字，
    #但貌似新版本的可以了（至少我现在用的5.27可以）
#2023年12月19日 V1.00 初代版本 仅针对文件是默认的ANSI编码的情况,使用前一定记得备份文件！！！！！

import os,os.path
from tkinter import filedialog

targetwords = "褒饼昌除待谍洱俘庚过糊积箭烬君魁例笼慢谬凝琵讫驱三升数她听妄锡淆\
旋妖引育札正铸佚冽邶埤荦蔟摭啐帻猃恺泯潺妪纨琮椠辇挲臊忑睚铨稞瘕颀螨簖酏觚鳊鼾"

msg = "请选择模式(输入序号)：\n"
msg += "1.我要逐个字确认\n"
msg += "2.直接全怼了别问我(默认)\n→："
cmd = input(msg)
if cmd == '1':
    flag_ask = True
else:
    flag_ask = False

workpath = os.getcwd() #获得当前工作目录

def start_replace(pathdir):
    print('开始检索目录：',pathdir)
    os.chdir(pathdir)
    for each_file in os.listdir('.'): #遍历当前目录下的文件，此时的each_file是已不包含路径的文件名字符串
        filetype = os.path.splitext(each_file)[1]
        if (os.path.isfile(each_file))and(filetype in [".c",".h"]):#筛选文件
            with open(each_file,"r") as rf:
                try:
                    datalist = rf.readlines()
                except UnicodeDecodeError:
                    print("文件“%s”编码错误"%(pathdir + '/' + each_file))
                    return 0
            filechanged = False
            for i in range(len(datalist)):
                for eachchar in targetwords: #挨个检索相关汉字
                    if eachchar in datalist[i]:
                        if datalist[i].count(eachchar) == datalist[i].count(eachchar+r'\xfd'):
                            break  #如果这里是已替换过的，跳过
                        msg = "\n文件：%s,行数：%d,内容：“%s”中发现汉字“%s”"%(each_file,i+1,datalist[i],eachchar)
                        if flag_ask:
                            msg += "\n是否替换(1:Y/0:N)："
                            cmd = input(msg)
                            if cmd in ['1','y','Y']:
                                while(eachchar+r'\xfd' in datalist[i]): #先反向替换一波，省的弄成双层的\xfd
                                    datalist[i] = datalist[i].replace(eachchar+r'\xfd',eachchar)
                                datalist[i] = datalist[i].replace(eachchar,eachchar+r'\xfd')
                                print("已替换为→：%s"%datalist[i])
                                filechanged = True
                            else:
                                print("已跳过")
                        else:
                            while(eachchar+r'\xfd' in datalist[i]): #先反向替换一波，省的弄成双层的\xfd
                                datalist[i] = datalist[i].replace(eachchar+r'\xfd',eachchar)
                            datalist[i] = datalist[i].replace(eachchar,eachchar+r'\xfd')
                            msg += "\n已替换为→：%s"%datalist[i]
                            print(msg)
                            filechanged = True
            if filechanged:
                with open(each_file,"w") as wf:
                    wf.writelines(datalist)
                    print("文件“%s”已保存！！！"%each_file)
        elif os.path.isdir(each_file):#如遇到文件夹，则开始递归
            start_replace(each_file) #递
            os.chdir('..') #归

start_replace(workpath)
cmd = input("所有替换工作已完成，任意键退出：")
