版本v0.1.1 ----1、新增显示输入法状态的功能;2、新增时间同步功能;3、新增翻译功能;4、新增咖啡因功能;5、新增屏幕取色功能;6、新增菜单栏管理
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
---
|
||||
--- 控制空闲时是否允许屏幕睡眠
|
||||
--- Created by sugood(https://github.com/sugood).
|
||||
--- DateTime: 2020/10/24 14:13
|
||||
---
|
||||
|
||||
if config ~=nil and config[1].caffeine == 'on' then
|
||||
print("设置状态栏")
|
||||
local menuBarItem = hs.menubar.new()
|
||||
menuBarItem:setTitle("")
|
||||
menuBarItem:setIcon("~/.hammerspoon/icon/caffeine-on.pdf")
|
||||
hs.caffeinate.set("displayIdle", true)
|
||||
else
|
||||
hs.caffeinate.set("displayIdle", false)
|
||||
end
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
---
|
||||
--- 公共函数
|
||||
--- Created by sugood(https://github.com/sugood).
|
||||
--- DateTime: 2020/10/24 14:13
|
||||
---
|
||||
local console = require("hs.console")
|
||||
version = "v0.1.1"
|
||||
configPath= "~/.hammerspoon/data/config.json"
|
||||
config = {}
|
||||
colorDialog = hs.dialog.color
|
||||
|
||||
function switchDict()
|
||||
if config[1].dictEngine == '百度' then
|
||||
config[1].dictEngine = '有道'
|
||||
else
|
||||
config[1].dictEngine = '百度'
|
||||
end
|
||||
hs.json.write(config,configPath, true, true)
|
||||
hs.reload()
|
||||
end
|
||||
|
||||
function switchTime()
|
||||
if config[1].isSyncTime == 'on' then
|
||||
config[1].isSyncTime = 'off'
|
||||
else
|
||||
if(stringIsEmpty(config[1].rootPassword)) then
|
||||
local result,subText = hs.dialog.textPrompt("输入开机密码", "时间同步操作需要开机密码", '', "确定", "取消", true)
|
||||
if result == "确定" and stringIsEmpty(subText) == false then
|
||||
config[1].rootPassword = subText
|
||||
config[1].isSyncTime = 'on'
|
||||
end
|
||||
else
|
||||
config[1].isSyncTime = 'on'
|
||||
end
|
||||
end
|
||||
hs.json.write(config,configPath, true, true)
|
||||
hs.reload()
|
||||
end
|
||||
|
||||
function switchCaffeine()
|
||||
if config[1].caffeine == 'on' then
|
||||
config[1].caffeine = 'off'
|
||||
else
|
||||
config[1].caffeine = 'on'
|
||||
end
|
||||
hs.json.write(config,configPath, true, true)
|
||||
hs.reload()
|
||||
end
|
||||
|
||||
--设置全局菜单栏
|
||||
function initMenu()
|
||||
macMenubar = hs.menubar.new()
|
||||
macMenubar:setTitle("")
|
||||
macMenubar:setIcon()
|
||||
macMenubar:setMenu( {
|
||||
{ title = "Reload config", fn = function()
|
||||
hs.reload()
|
||||
end },
|
||||
{ title = "Open console", fn = function() hs.openConsole() end },
|
||||
{ title = "Relaunch", fn = function() hs.relaunch() end },
|
||||
{ title = "-" },
|
||||
{ title = "翻译平台:" .. config[1].dictEngine, fn = function()
|
||||
if (hs.dialog.blockAlert("支持百度和有道翻译,确认切换?","有道翻译需先申请有道云API","确定","取消","informational") == "确定") then
|
||||
switchDict()
|
||||
end
|
||||
end },
|
||||
{ title = "输入appID", fn = function()
|
||||
if(config[1].dictEngine == '有道') then
|
||||
local result,subText = hs.dialog.textPrompt("输入appID", "请通过有道云API获取appkey", config[1].youdaoAppid, "确定", "取消", false)
|
||||
if result == "确定" then
|
||||
config[1].youdaoAppid = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
end
|
||||
elseif(config[1].dictEngine == '百度') then
|
||||
local result,subText = hs.dialog.textPrompt("输入appID", "百度翻译可不修改", config[1].baiduAppid, "确定", "取消", true)
|
||||
if result == "确定" then
|
||||
config[1].baiduAppid = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
end
|
||||
end
|
||||
end },
|
||||
{ title = "输入appSecret", fn = function()
|
||||
if(config[1].dictEngine == '有道') then
|
||||
local result,subText = hs.dialog.textPrompt("输入appSecret", "请通过有道云API获取appSecret", config[1].youdaoAppSecret, "确定", "取消", false)
|
||||
if result == "确定" then
|
||||
config[1].youdaoAppSecret = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
end
|
||||
elseif(config[1].dictEngine == '百度') then
|
||||
local result,subText = hs.dialog.textPrompt("输入appSecret", "百度翻译可不修改", config[1].baiduAppSecret, "确定", "取消", true)
|
||||
if result == "确定" then
|
||||
config[1].baiduAppSecret = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
end
|
||||
end
|
||||
end },
|
||||
{ title = "-" },
|
||||
{ title = "时间同步:" .. config[1].isSyncTime, fn = function()
|
||||
switchTime()
|
||||
end },
|
||||
{ title = "输入开机密码", fn = function()
|
||||
local result,subText = hs.dialog.textPrompt("输入开机密码", "时间同步操作需要开机密码", config[1].rootPassword, "确定", "取消", true)
|
||||
if result == "确定" then
|
||||
config[1].rootPassword = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
end
|
||||
end },
|
||||
{ title = "-" },
|
||||
{ title = "屏幕取色", fn = function()
|
||||
hs.openConsole(true)
|
||||
colorDialog.show()
|
||||
colorDialog.mode("RGB")
|
||||
colorDialog.callback(function(a,b)
|
||||
if b then
|
||||
hs.closeConsole()
|
||||
end
|
||||
end)
|
||||
hs.closeConsole()
|
||||
end },
|
||||
{ title = "-" },
|
||||
{ title = "咖啡因:" .. config[1].caffeine, fn = function()
|
||||
switchCaffeine()
|
||||
end },
|
||||
{ title = "-" },
|
||||
{ title = "打开键盘偏好设置", fn = function() hs.osascript.applescript([[
|
||||
tell application "System Preferences"
|
||||
reveal anchor "InputSources" of pane "com.apple.preference.keyboard"
|
||||
activate
|
||||
end tell ]]
|
||||
) end },
|
||||
{ title = "-" },
|
||||
{ title = "关于", fn = function()
|
||||
if (hs.dialog.blockAlert("当前版本:"..version,"整理了一些能够提高效率的脚本,打开主页查看详细说明","确定","取消","informational") == "确定") then
|
||||
hs.urlevent.openURL("https://github.com/sugood/hammerspoon")
|
||||
end
|
||||
end },
|
||||
})
|
||||
end
|
||||
|
||||
function initData()
|
||||
if hs.json.read(configPath) ~= nil then
|
||||
config = hs.json.read(configPath)
|
||||
end
|
||||
initMenu()
|
||||
-- 修改全局alert样式
|
||||
hs.alert.defaultStyle.strokeColor = {white = 1, alpha = 0}
|
||||
hs.alert.defaultStyle.fillColor = {white = 0.05, alpha = 0.75}
|
||||
hs.alert.defaultStyle.radius = 10
|
||||
--清空打印信息
|
||||
console.clearConsole()
|
||||
--
|
||||
colorDialog.mode("RGB")
|
||||
end
|
||||
|
||||
initData()
|
||||
|
||||
-- 字符串判空
|
||||
function stringIsEmpty(str)
|
||||
return str == nil or str == ''
|
||||
end
|
||||
|
||||
--生成url编码
|
||||
function decodeURI(s)
|
||||
s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
|
||||
return string.gsub(s, " ", "+")
|
||||
end
|
||||
|
||||
--截取UTF8字符
|
||||
function SubStringUTF8(str, startIndex, endIndex)
|
||||
if startIndex < 0 then
|
||||
startIndex = SubStringGetTotalIndex(str) + startIndex + 1;
|
||||
end
|
||||
|
||||
if endIndex ~= nil and endIndex < 0 then
|
||||
endIndex = SubStringGetTotalIndex(str) + endIndex + 1;
|
||||
end
|
||||
|
||||
if endIndex == nil then
|
||||
return string.sub(str, SubStringGetTrueIndex(str, startIndex));
|
||||
else
|
||||
return string.sub(str, SubStringGetTrueIndex(str, startIndex), SubStringGetTrueIndex(str, endIndex + 1) - 1);
|
||||
end
|
||||
end
|
||||
|
||||
--获取中英混合UTF8字符串的真实字符数量
|
||||
function SubStringGetTotalIndex(str)
|
||||
local curIndex = 0;
|
||||
local i = 1;
|
||||
local lastCount = 1;
|
||||
repeat
|
||||
lastCount = SubStringGetByteCount(str, i)
|
||||
i = i + lastCount;
|
||||
curIndex = curIndex + 1;
|
||||
until(lastCount == 0);
|
||||
return curIndex - 1;
|
||||
end
|
||||
|
||||
function SubStringGetTrueIndex(str, index)
|
||||
local curIndex = 0;
|
||||
local i = 1;
|
||||
local lastCount = 1;
|
||||
repeat
|
||||
lastCount = SubStringGetByteCount(str, i)
|
||||
i = i + lastCount;
|
||||
curIndex = curIndex + 1;
|
||||
until(curIndex >= index);
|
||||
return i - lastCount;
|
||||
end
|
||||
|
||||
--返回当前字符实际占用的字符数
|
||||
function SubStringGetByteCount(str, index)
|
||||
local curByte = string.byte(str, index)
|
||||
local byteCount = 1;
|
||||
if curByte == nil then
|
||||
byteCount = 0
|
||||
elseif curByte > 0 and curByte <= 127 then
|
||||
byteCount = 1
|
||||
elseif curByte>=192 and curByte<=223 then
|
||||
byteCount = 2
|
||||
elseif curByte>=224 and curByte<=239 then
|
||||
byteCount = 3
|
||||
elseif curByte>=240 and curByte<=247 then
|
||||
byteCount = 4
|
||||
end
|
||||
return byteCount;
|
||||
end
|
||||
@@ -0,0 +1,205 @@
|
||||
---
|
||||
--- 快速打开翻译,支持百度和有道翻译API
|
||||
--- 有道API需要用户自行申请。
|
||||
--- Created by sugood(https://github.com/sugood).
|
||||
--- DateTime: 2020/10/23 11:12
|
||||
---
|
||||
|
||||
|
||||
local chooser = require("hs.chooser")
|
||||
local menubar = hs.menubar.new()
|
||||
local dictHistoryPath= "~/.hammerspoon/data/dictHistory.json"
|
||||
local ydUrl = 'https://openapi.youdao.com/api'
|
||||
local bdUrl = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
|
||||
local bdWeburl = 'https://fanyi.baidu.com/#'
|
||||
local ydWeburl = 'http://youdao.com/w/'
|
||||
|
||||
local mChooser
|
||||
local searchResult = {}
|
||||
local isFirst = true
|
||||
function truncate(q)
|
||||
if q == nil or q == '' then
|
||||
return ''
|
||||
end
|
||||
local len = SubStringGetTotalIndex(q)
|
||||
if (len <= 20) then
|
||||
return q
|
||||
else
|
||||
return SubStringUTF8(q,1,10)..len..SubStringUTF8(q,len-9)
|
||||
end
|
||||
end
|
||||
|
||||
function newWebview()
|
||||
local cscreen = hs.screen.mainScreen()
|
||||
local cres = cscreen:fullFrame()
|
||||
sheetView = hs.webview.newBrowser({
|
||||
x = cres.x+cres.w*0.15/2,
|
||||
y = cres.y+cres.h*0.25/2,
|
||||
w = cres.w*0.85,
|
||||
h = cres.h*0.75
|
||||
})
|
||||
sheetView:windowTitle("CheatSheets")
|
||||
sheetView:windowStyle("utility")
|
||||
sheetView:titleVisibility("hidden")
|
||||
sheetView:allowGestures(true)
|
||||
sheetView:allowNewWindows(false)
|
||||
sheetView:allowTextEntry(true)
|
||||
sheetView:closeOnEscape(true)
|
||||
sheetView:bringToFront(false)
|
||||
sheetView:darkMode(true)
|
||||
sheetView:reload(false)
|
||||
sheetView:level(hs.drawing.windowLevels.mainMenu)
|
||||
end
|
||||
|
||||
-- 右键弹出菜单
|
||||
local rightClickCallbackFn = function(index)
|
||||
if index and index > 0 then
|
||||
local selectResult = mChooser:selectedRowContents(index)
|
||||
if selectResult == nil or stringIsEmpty(selectResult.text) then
|
||||
return
|
||||
end
|
||||
menubar = hs.menubar.new(false)
|
||||
menubar:setTitle("Hidden Menu")
|
||||
menubar:setMenu( {
|
||||
{ title = "查看详情", fn = function()
|
||||
hs.dialog.blockAlert(selectResult.text, selectResult.subText,"确定","","informational")
|
||||
end },
|
||||
{ title = "查看网页", fn = function()
|
||||
sheetView:url(selectResult.webUrl):show()
|
||||
end },
|
||||
})
|
||||
menubar:popupMenu(hs.mouse.getAbsolutePosition(), true)
|
||||
end
|
||||
end
|
||||
|
||||
function getBaiduApi(q)
|
||||
headers = {ContentType = "application/x-www-form-urlencoded;charset=utf-8"}
|
||||
salt = tostring(hs.timer.secondsSinceEpoch()*1000)
|
||||
curtime = tostring(os.time())
|
||||
geturl = "q="..q.."&from=auto&to=auto&appid=".. config[1].baiduAppid .."&salt="..salt.."&sign="..hs.hash.MD5(config[1].baiduAppid ..q..salt..config[1].baiduAppSecret)
|
||||
--print('geturl:'..geturl)
|
||||
|
||||
hs.http.doAsyncRequest(bdUrl,'POST',geturl,headers,function(code, body, htable)
|
||||
if code ~= 200 then
|
||||
print('get weather error:'..code)
|
||||
return
|
||||
else
|
||||
searchResult = {}
|
||||
results = hs.json.decode(body)
|
||||
print('results:'..hs.inspect(results))
|
||||
if(results['trans_result']) then
|
||||
item = {}
|
||||
item.text = results['trans_result'][1].dst
|
||||
item.subText = q
|
||||
item.webUrl = bdWeburl..results['from'].."/"..results['to'].."/"..decodeURI(q)
|
||||
table.insert(searchResult,1,item)
|
||||
end
|
||||
mChooser:choices(searchResult)
|
||||
hs.json.write(searchResult,dictHistoryPath, true, true)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
function getYoudaoApi(q)
|
||||
headers = {ContentType = "application/x-www-form-urlencoded;charset=utf-8"}
|
||||
salt = tostring(hs.timer.secondsSinceEpoch()*1000)
|
||||
curtime = tostring(os.time())
|
||||
geturl = "q="..q.."&from=auto&to=auto&signType=v3&curtime="..curtime.."&appKey="..config[1].youdaoAppid..
|
||||
"&salt="..salt.."&sign="..hs.hash.SHA256(config[1].youdaoAppid..truncate(q)..salt..curtime..config[1].youdaoAppSecret)
|
||||
--print('geturl:'..geturl)
|
||||
|
||||
hs.http.doAsyncRequest(ydUrl,'POST',geturl,headers,function(code, body, htable)
|
||||
if code ~= 200 then
|
||||
print('get weather error:'..code)
|
||||
return
|
||||
else
|
||||
searchResult = {}
|
||||
results = hs.json.decode(body)
|
||||
print('results:'..hs.inspect(results))
|
||||
if(results['web']) then
|
||||
--逆序插入
|
||||
for i=#results['web'],1,-1 do
|
||||
item = {}
|
||||
item.text = table.concat(results['web'][i].value,", ")
|
||||
item.subText = results['web'][i].key
|
||||
item.webUrl = ydWeburl..decodeURI(item.subText)
|
||||
table.insert(searchResult,1,item)
|
||||
end
|
||||
end
|
||||
if(results['basic']) then
|
||||
if (results['basic']['exam_type']) then
|
||||
item = {}
|
||||
item.text = table.concat(results['basic']['exam_type'],', ')
|
||||
item.subText = q
|
||||
item.webUrl = ydWeburl..decodeURI(item.subText)
|
||||
table.insert(searchResult,1,item)
|
||||
end
|
||||
if (results['basic']['explains']) then
|
||||
for i=#results['basic']['explains'],1,-1 do
|
||||
item = {}
|
||||
item.text = results['basic']['explains'][i]
|
||||
item.subText = q
|
||||
item.webUrl = ydWeburl..decodeURI(item.subText)
|
||||
table.insert(searchResult,1,item)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
if(results['translation']) then
|
||||
item = {}
|
||||
item.text = table.concat(results['translation'])
|
||||
item.subText = q
|
||||
item.webUrl = ydWeburl..decodeURI(item.subText)
|
||||
table.insert(searchResult,1,item)
|
||||
end
|
||||
mChooser:choices(searchResult)
|
||||
hs.json.write(searchResult,dictHistoryPath, true, true)
|
||||
end
|
||||
end)
|
||||
end
|
||||
-- 粘贴选中的片段
|
||||
local completionFn = function(result)
|
||||
if result then
|
||||
hs.pasteboard.setContents(result.text)
|
||||
--hs.eventtap.keyStroke({ "cmd" }, "V")
|
||||
print("keywords:"..result.text)
|
||||
end
|
||||
end
|
||||
-- 监听输入框
|
||||
local queryChangedCallbackFn = function(result)
|
||||
print("changekeywords:"..result)
|
||||
if result and #result > 0 then
|
||||
if config[1].dictEngine == '百度' then
|
||||
getBaiduApi(result)
|
||||
else
|
||||
getYoudaoApi(result)
|
||||
end
|
||||
else
|
||||
if(isFirst) then
|
||||
isFirst = false
|
||||
else
|
||||
searchResult = {}
|
||||
mChooser:choices(searchResult)
|
||||
hs.json.write(searchResult,dictHistoryPath, true, true)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function initData()
|
||||
newWebview()
|
||||
-- 选取片段内容(按下快捷键时显示片段列表,点击选中的快捷键将自动粘贴)
|
||||
hs.hotkey.bind(hyperCmd, "F", function ()
|
||||
isFirst = true
|
||||
if hs.json.read(dictHistoryPath) ~= nil then
|
||||
searchResult = hs.json.read(dictHistoryPath)
|
||||
end
|
||||
mChooser = chooser.new(completionFn)
|
||||
:choices(searchResult)
|
||||
:queryChangedCallback(queryChangedCallbackFn)
|
||||
:rightClickCallback(rightClickCallbackFn)
|
||||
:searchSubText(true)
|
||||
:show()
|
||||
end)
|
||||
end
|
||||
|
||||
initData()
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
hyper = {"cmd", "ctrl", "alt"}
|
||||
hyperShift = {"alt", "shift"}
|
||||
hyperCtrl = {"alt", "ctrl"}
|
||||
hyperAlt = {"ctrl", "alt", "shift"}
|
||||
hyperAlt = {"ctrl", "alt", "shift"}
|
||||
hyperCmd = {"alt", "cmd"}
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
--- 在状态栏中显示输入法的状态
|
||||
--- 例如:大小写状态,中英文状态,目前只适配搜狗输入法
|
||||
--- Created by sugood(https://github.com/sugood).
|
||||
--- DateTime: 2020/10/24 11:12
|
||||
---
|
||||
|
||||
local sougouId = 'com.sogou.inputmethod.sogou.pinyin'
|
||||
local shuangpinId = 'com.apple.inputmethod.SCIM.Shuangpin'
|
||||
local abcId = 'com.apple.keylayout.ABC'
|
||||
|
||||
local mEventtap
|
||||
function isChinese()
|
||||
-- 用于保存当前输入法
|
||||
local currentSourceID = hs.keycodes.currentSourceID()
|
||||
return (currentSourceID == sougouId or currentSourceID == shuangpinId)
|
||||
end
|
||||
|
||||
--解决hs.eventtap.new 有时候会卡死的问题。需要每秒检查下监听状态。如果卡死了就重新启动
|
||||
local listenerEvent = function()
|
||||
if mEventtap:isEnabled()==false then
|
||||
print("重启监听事件")
|
||||
mEventtap:start()
|
||||
end
|
||||
end
|
||||
function initData()
|
||||
local reverse = true
|
||||
local imgInputAbc = '~/.hammerspoon/icon/input_abc.pdf'
|
||||
local imgInputEn = '~/.hammerspoon/icon/input_en.pdf'
|
||||
local imgInputCn = '~/.hammerspoon/icon/input_cn.pdf'
|
||||
local imgInputU = '~/.hammerspoon/icon/input_u.pdf'
|
||||
|
||||
--初始化默认是英文输入法
|
||||
hs.keycodes.currentSourceID(abcId)
|
||||
if hs.hid.capslock.get() then
|
||||
macMenubar:setIcon(imgInputU)
|
||||
else
|
||||
if(isChinese()) then
|
||||
macMenubar:setIcon(imgInputCn)
|
||||
else
|
||||
macMenubar:setIcon(imgInputAbc)
|
||||
end
|
||||
end
|
||||
mEventtap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, function(event)
|
||||
--获取shift按键信息
|
||||
if event:getKeyCode() == 56 and event:getFlags().shift then
|
||||
if (isChinese()) then
|
||||
hs.hid.led.set('caps',false)
|
||||
hs.alert.closeSpecific(showUUID)
|
||||
if reverse then
|
||||
reverse = false
|
||||
macMenubar:setIcon(imgInputEn)
|
||||
else
|
||||
reverse = true
|
||||
macMenubar:setIcon(imgInputCn)
|
||||
end
|
||||
else
|
||||
if hs.hid.capslock.get()==false then
|
||||
reverse = false
|
||||
macMenubar:setIcon(imgInputAbc)
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
--获取capslock按键信息
|
||||
tab =hs.eventtap.checkKeyboardModifiers("capslock")
|
||||
local isCaptLock = tab["capslock"]
|
||||
if isCaptLock then
|
||||
if hs.hid.capslock.get() then
|
||||
hs.hid.led.set('caps',true)
|
||||
else
|
||||
hs.hid.led.set('caps',false)
|
||||
hs.alert.closeAll(0)
|
||||
hs.alert.show("键盘小写 🔤- OFF")
|
||||
if(isChinese()) then
|
||||
if(reverse) then
|
||||
macMenubar:setIcon(imgInputCn)
|
||||
else
|
||||
macMenubar:setIcon(imgInputEn)
|
||||
end
|
||||
else
|
||||
macMenubar:setIcon(imgInputAbc)
|
||||
end
|
||||
end
|
||||
else
|
||||
if hs.hid.capslock.get() then
|
||||
hs.hid.led.set('caps',true)
|
||||
hs.alert.closeAll(0)
|
||||
hs.alert.show("键盘大写 🅰️- ON")
|
||||
macMenubar:setIcon(imgInputU)
|
||||
else
|
||||
--print("小写2")
|
||||
hs.hid.led.set('caps',false)
|
||||
end
|
||||
end
|
||||
return false
|
||||
end)
|
||||
mEventtap:start()
|
||||
hs.timer.doEvery(1, listenerEvent)
|
||||
hs.keycodes.inputSourceChanged(function()
|
||||
-- 用于保存当前输入法
|
||||
local currentSourceID = hs.keycodes.currentSourceID()
|
||||
|
||||
-- 如果当前输入法和上一个输入法相同,则直接返回
|
||||
if currentSourceID == lastSourceID then
|
||||
return
|
||||
end
|
||||
-- 用于保存当前输入法
|
||||
local currentSourceID = hs.keycodes.currentSourceID()
|
||||
hs.alert.closeAll(0)
|
||||
-- 判断是系统自带的 ABC还是中文输入法
|
||||
if (currentSourceID == abcId) then
|
||||
--hs.alert.show("ABC")
|
||||
macMenubar:setIcon(imgInputAbc)
|
||||
reverse = false
|
||||
elseif (currentSourceID == sougouId or currentSourceID == shuangpinId) then
|
||||
--hs.alert.show("中文")
|
||||
reverse = true
|
||||
macMenubar:setIcon(imgInputCn)
|
||||
end
|
||||
-- 保存最后一个输入法源名称ds
|
||||
lastSourceID = currentSourceID
|
||||
end)
|
||||
end
|
||||
-- 初始化
|
||||
initData()
|
||||
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
-----
|
||||
----- 格式化Json
|
||||
----- Created by sugood(https://github.com/sugood).
|
||||
----- DateTime: 2020/10/19 10:34
|
||||
-----
|
||||
--
|
||||
--
|
||||
|
||||
local function generateHtml()
|
||||
|
||||
local html = [[
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Json格式化高亮展示工具</title>
|
||||
|
||||
<style>
|
||||
body { height: 100%; margin:0; font-family:"微软雅黑"; font-size:12px; }
|
||||
.pdiv { height: 85%; position: absolute; }
|
||||
.title { height: auto; font-size:20px; text-align:center; margin-top: 5px; margin-bottom: 20px;}
|
||||
.author { height: auto; width: 100%; font-size:12px; text-align:center; margin-top: 30px; margin-bottom: 20px;}
|
||||
table { height: 100%; width:100%; border-collapse:collapse; }
|
||||
table .tdLeft { width:85%; text-align:left; padding-left: 10px;padding-right: 10px;}
|
||||
table .tdmid { width:150px; text-align:center; margin: 0px; padding: 0px;}
|
||||
table .tdRight { width:85%; padding-right: 30px;text-align:left; }
|
||||
table textarea { width:100%; height:100%; font-size:14px; padding-top: 10px; padding-left: 10px; outline: none; border-radius: 15px; border: 2px solid #8AC007; }
|
||||
#container { width:100%; height:100%; font-size:14px; padding-top: 10px; padding-left: 10px; border-radius: 15px; border: 2px solid #8AC007;}
|
||||
pre{white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; margin: 0px; padding: 5px;}
|
||||
pre .string { color: green; }
|
||||
pre .number { color: darkorange; }
|
||||
pre .boolean { color: blue; }
|
||||
pre .null { color: magenta; }
|
||||
.key { color: red; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="pdiv">
|
||||
<div class="title" >Json格式化高亮展示工具</div>
|
||||
<table style="table-layout:fixed">
|
||||
<tr>
|
||||
<!-- <td class="tdLeft" nowrap>请输入要展示的Json:</td> -->
|
||||
<td class="tdLeft">
|
||||
<input style="width:auto; margin: 10px;" type="button" value="复制" onClick="copySource()">
|
||||
<textarea name = "jsonContent" id="jsonContent" ></textarea>
|
||||
</td>
|
||||
<td class="tdmid"><input style="width:80%;" type="button" value="格式化JSON >>" onClick="showJson()"></td>
|
||||
<td class="tdRight">
|
||||
<input style="width:auto; margin: 10px;" type="button" value="复制" onClick="copyResult()">
|
||||
<pre id="container"></pre>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div class="author">
|
||||
<a href="https://github.com/sugood" target="_blank">By: github.com/sugood</a>
|
||||
</div>
|
||||
<div class="tips" id="tips">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script type="text/javascript">
|
||||
|
||||
function copySource(){
|
||||
var obj = document.getElementById('jsonContent');
|
||||
//选择当前对象
|
||||
obj.select();
|
||||
try{
|
||||
if(document.execCommand("Copy","false",null)){
|
||||
alert("复制成功!");
|
||||
}
|
||||
}catch(err){
|
||||
alert("复制错误!");
|
||||
}
|
||||
}
|
||||
|
||||
function copyResult(){
|
||||
var text = document.getElementById('container').innerText;
|
||||
const input = document.createElement('textarea');
|
||||
input.value = text;
|
||||
input.setAttribute('readonly', 'readonly');
|
||||
document.body.appendChild(input);
|
||||
input.select();
|
||||
try{
|
||||
if(document.execCommand('Copy')){
|
||||
alert('复制成功');
|
||||
}
|
||||
}catch(err){
|
||||
alert("复制错误!");
|
||||
}
|
||||
document.body.removeChild(input);
|
||||
}
|
||||
|
||||
function syntaxHighlight(json) {
|
||||
if (typeof json != 'string') {
|
||||
json = JSON.stringify(json, undefined, 4);
|
||||
}
|
||||
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
|
||||
var cls = 'number';
|
||||
if (/^"/.test(match)) {
|
||||
if (/:$/.test(match)) {
|
||||
cls = 'key';
|
||||
} else {
|
||||
cls = 'string';
|
||||
}
|
||||
} else if (/true|false/.test(match)) {
|
||||
cls = 'boolean';
|
||||
} else if (/null/.test(match)) {
|
||||
cls = 'null';
|
||||
}
|
||||
return '<span class="' + cls + '">' + match + '</span>';
|
||||
});
|
||||
}
|
||||
|
||||
function showJson(){
|
||||
var text = document.getElementById('jsonContent').value
|
||||
if (text!="" && text!=null){
|
||||
try {
|
||||
var result = JSON.stringify(JSON.parse(text), null, 4);//将字符串转换成json对象
|
||||
highLineResult = syntaxHighlight(result);
|
||||
document.getElementById('container').innerHTML= highLineResult;
|
||||
localStorage.setItem("jsonFormatSource",text);
|
||||
localStorage.setItem("jsonFormatResult",highLineResult);
|
||||
} catch(e) {
|
||||
document.getElementById('container').innerText= '异常信息:'+e ;
|
||||
}
|
||||
}else{
|
||||
document.getElementById("jsonContent").value = "请输入json文本";
|
||||
document.getElementById('container').innerHTML= "显示Json格式化后的效果";
|
||||
localStorage.setItem("jsonFormatSource","请输入json文本");
|
||||
localStorage.setItem("jsonFormatResult","显示Json格式化后的效果");
|
||||
}
|
||||
};
|
||||
|
||||
var jsonFormatSource = localStorage.getItem("jsonFormatSource");
|
||||
if (jsonFormatSource!="" && jsonFormatSource!=null){
|
||||
document.getElementById("jsonContent").value=localStorage.getItem("jsonFormatSource");
|
||||
}else{
|
||||
document.getElementById("jsonContent").value = "请输入json文本"
|
||||
}
|
||||
var jsonFormatResult = localStorage.getItem("jsonFormatResult");
|
||||
if (jsonFormatResult!="" && jsonFormatResult!=null){
|
||||
document.getElementById("container").innerHTML=localStorage.getItem("jsonFormatResult");
|
||||
}else{
|
||||
document.getElementById("jsonContent").value = "显示Json格式化后的效果"
|
||||
}
|
||||
|
||||
</script>
|
||||
</html>
|
||||
]]
|
||||
|
||||
return html
|
||||
end
|
||||
|
||||
|
||||
--- KSheet:hide()
|
||||
--- Method
|
||||
--- Hide the cheatsheet view.
|
||||
function hide(time)
|
||||
sheetView:hide(time)
|
||||
end
|
||||
|
||||
function init()
|
||||
local cscreen = hs.screen.mainScreen()
|
||||
local cres = cscreen:fullFrame()
|
||||
sheetView = hs.webview.newBrowser({
|
||||
x = cres.x+cres.w*0.15/2,
|
||||
y = cres.y+cres.h*0.25/2,
|
||||
w = cres.w*0.85,
|
||||
h = cres.h*0.75
|
||||
})
|
||||
sheetView:windowTitle("CheatSheets")
|
||||
sheetView:windowStyle("utility")
|
||||
sheetView:titleVisibility("hidden")
|
||||
sheetView:allowGestures(true)
|
||||
sheetView:allowNewWindows(false)
|
||||
sheetView:allowTextEntry(true)
|
||||
sheetView:closeOnEscape(true)
|
||||
sheetView:bringToFront(false)
|
||||
sheetView:darkMode(true)
|
||||
sheetView:reload(false)
|
||||
sheetView:level(hs.drawing.windowLevels.mainMenu)
|
||||
end
|
||||
|
||||
--- KSheet:show()
|
||||
--- Method
|
||||
--- Show current application's keybindings in a view.
|
||||
function show(time)
|
||||
local webcontent = generateHtml()
|
||||
sheetView:html(webcontent, "http://localhost")
|
||||
sheetView:show(time)
|
||||
end
|
||||
|
||||
function toggle()
|
||||
if sheetView and sheetView:hswindow() and sheetView:hswindow():isVisible() then
|
||||
hide(2)
|
||||
else
|
||||
show(2)
|
||||
end
|
||||
end
|
||||
|
||||
init()
|
||||
|
||||
-- 添加片段(按下快捷键时做一个复制操作,并记录复制的内容到片段列表中)
|
||||
hs.hotkey.bind(hyperCmd, "G", function ()
|
||||
toggle()
|
||||
end)
|
||||
+4
-9
@@ -1,7 +1,5 @@
|
||||
local chooser = require("hs.chooser")
|
||||
local console = require("hs.console")
|
||||
|
||||
console.clearConsole()
|
||||
local historyPath= "~/.hammerspoon/data/history.json"
|
||||
local maxLength = 1000
|
||||
local history = {}
|
||||
@@ -24,10 +22,7 @@ function duplicate(table,keys)
|
||||
end
|
||||
return false
|
||||
end
|
||||
-- 字符串判空
|
||||
function isEmpty(str)
|
||||
return str == nil or str == ''
|
||||
end
|
||||
|
||||
-- 查询text是否存在并返回索引index
|
||||
-- 等于0为没有查询到,大于0为查询到
|
||||
function searchByText(table,text)
|
||||
@@ -120,7 +115,7 @@ end
|
||||
local rightClickCallbackFn = function(index)
|
||||
if index and index > 0 then
|
||||
local selectResult = mChooser:selectedRowContents(index)
|
||||
if selectResult == nil or isEmpty(selectResult.text) then
|
||||
if selectResult == nil or stringIsEmpty(selectResult.text) then
|
||||
return
|
||||
end
|
||||
index = searchByText(history,selectResult.text)
|
||||
@@ -160,7 +155,7 @@ local rightClickCallbackFn = function(index)
|
||||
end
|
||||
end
|
||||
-- 选取片段内容(按下快捷键时显示片段列表,点击选中的快捷键将自动粘贴)
|
||||
hs.hotkey.bind({ "ctrl", "cmd" }, "V", function ()
|
||||
hs.hotkey.bind(hyperCmd, "V", function ()
|
||||
mChooser = chooser.new(completionFn)
|
||||
:choices(history)
|
||||
:rightClickCallback(rightClickCallbackFn)
|
||||
@@ -168,7 +163,7 @@ hs.hotkey.bind({ "ctrl", "cmd" }, "V", function ()
|
||||
:show()
|
||||
end)
|
||||
-- 添加片段(按下快捷键时做一个复制操作,并记录复制的内容到片段列表中)
|
||||
hs.hotkey.bind({"ctrl", "cmd"}, "A", function ()
|
||||
hs.hotkey.bind(hyperCmd, "X", function ()
|
||||
bindCopyKey()
|
||||
if hs.dialog.blockAlert("添加片段:‘|’为分隔符,建议按如下格式","内容|keyword|示例|说明","确定","取消","informational") == "确定" then
|
||||
addToHistory()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
--- 时间同步,开启后在系统或屏幕唤醒后自动同步一次时间
|
||||
--- Created by sugood(https://github.com/sugood).
|
||||
--- DateTime: 2020/10/23 11:12
|
||||
---
|
||||
|
||||
function execTimeSync()
|
||||
local shell_command = 'expect ~/.hammerspoon/timesync/timesync.sh '.. config[1].rootPassword
|
||||
result = table.pack(hs.execute(shell_command,true))
|
||||
print(result[1])
|
||||
end
|
||||
function caffeinateCallback(eventType)
|
||||
if (eventType == hs.caffeinate.watcher.screensDidSleep) then
|
||||
print("screensDidSleep")
|
||||
elseif (eventType == hs.caffeinate.watcher.screensDidWake) then
|
||||
execTimeSync()
|
||||
hs.reload()
|
||||
print("screensDidWake")
|
||||
elseif (eventType == hs.caffeinate.watcher.systemDidWake) then
|
||||
execTimeSync()
|
||||
hs.reload()
|
||||
print("systemDidWake")
|
||||
elseif (eventType == hs.caffeinate.watcher.screensDidLock) then
|
||||
print("screensDidLock")
|
||||
elseif (eventType == hs.caffeinate.watcher.screensDidUnlock) then
|
||||
print("screensDidUnlock")
|
||||
end
|
||||
end
|
||||
|
||||
function initData()
|
||||
if config ~=nil and config[1].isSyncTime == 'on' then
|
||||
caffeinateWatcher = hs.caffeinate.watcher.new(caffeinateCallback)
|
||||
caffeinateWatcher:start()
|
||||
|
||||
-- 添加片段(按下快捷键时做一个复制操作,并记录复制的内容到片段列表中)
|
||||
hs.hotkey.bind(hyperCmd, "T", function ()
|
||||
if hs.json.read(configPath) ~= nil then
|
||||
config = hs.json.read(configPath)
|
||||
end
|
||||
if(stringIsEmpty(config[1].rootPassword)) then
|
||||
local result,subText = hs.dialog.textPrompt("输入开机密码", "时间同步操作需要开机密码", '', "确定", "取消", true)
|
||||
if result == "确定" then
|
||||
if(stringIsEmpty(subText) == false) then
|
||||
config[1].rootPassword = subText
|
||||
hs.json.write(config,configPath, true, true)
|
||||
execTimeSync()
|
||||
hs.alert.show('同步时间')
|
||||
end
|
||||
end
|
||||
else
|
||||
execTimeSync()
|
||||
hs.alert.show('同步时间')
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
-- 初始化,读取本地数据
|
||||
initData()
|
||||
|
||||
Reference in New Issue
Block a user