<commit_before>###
# background 后台运行
创建右键菜单，监听菜单刷新事件
###
chrome.contextMenus.onClicked.addListener((info, tab)->
  ### 单击事件 ###
  console.debug 'onClickHandler'
  type = info.menuItemId[0]
  id = info.menuItemId[1..]
  type = getType(type)
  value = getValue(info, tab, type)
  openTab(id, type, value, tab)
)
chrome.runtime.onStartup.addListener(menuReset)
chrome.runtime.onInstalled.addListener(->
  console.debug 'installed'
  all = JU.lsGet('all', [])
  if all.length == 0
    JU.syncFetch('/init.json', (result)->
      JU.lsSet('all', JSON.parse(result))
      _gaq.push(['_trackEvent', 'db', 'ninit'])
    )
  console.debug 'start'
  ci18n = getCi18n()
  if not JU.lsGet('three_run', false)
    i18n = ci18n.getMessage('i18n')
    JU.lsSet('en', true)
    if i18n == 'cn'
      JU.lsSet('zh_CN', true)
      data =
        txtSelect: ['baidu', 'translate', 'zdic', 'amazon', 'taobao']
        picSelect: ['google_pic', 'baidu_pic', 'qr_decode']
        linSelect: ['weibo_lin', 'gmail_lin', 'qr_lin']
        menSelect: ['i_title']
    else if i18n == 'tw'
      JU.lsSet('zh_TW', true)
    else if i18n == 'ru'
      JU.lsSet('ru', true)
    if not data
      data =
        txtSelect: ['bing', 'translate', 'Amazon_com']
        picSelect: ['google_pic', 'su_pic']
        linSelect: ['gmail_lin', 'qr_lin']
        menSelect: ['i_title']
    for key of data
      JU.lsSet(key, JU.lsGet(key, data[key]))
    chrome.tabs.create({url:'options.html', selected: true})
    JU.lsSet('three_run', true)
    _gaq.push(['_trackEvent', 'option', 'init'])
  menuReset()
)

#getUrls = (custom, ids, fun)->
#  ### 根据ids查找URL,返回URL列表 ###
#  for id in ids
#    _gaq.push(['_trackEvent', 'menu', id])
#    findUrl(id, (ur)->
#      fun(ur)
#    )
#    for c in custom
#      if c[0] == id
#        fun(c[1])
getValue = (info, tab, type)->
  ### 根据类型决定参数值 ###
  {
    'men': tab.url
    'txt': info.selectionText
    'pic': info.srcUrl
    'lin': info.linkUrl
  }[type]

show = (url, value, tab, back=false, incognito=false, x=1, type='txt')->
  ### 根据网址、变量打开页面 网址,变量,后台,类型,隐身,tab,左右###
  if /%l|%L/g.test(url)
    url = url.replace(/%l|%L/g, encodeURIComponent(tab.title))
  if /%s|%S/g.test(url)
    url = url.replace(/%s|%S/g, encodeURIComponent(value))
    #u = /%u|%U/g
    #if u.test(url)
    #  u.lastIndex=0
    #  url = url.replace(u, encoden(value))
  if /%g|%G/g.test(url)
    url = url.replace(/%g|%G/g, encodeToGbk(value))
  if /%t|%T/g.test(url)
    url = url.replace(/%t|%T/g, encodeToBig5(value))
  if /%p|%P/g.test(url)
    url = url.replace(/%p|%P/g, encodeURIComponent(readClipboard()))
  if /%u|%U/g.test(url) and tab
    doman = tab.url.split('/')[2]
    url = url.replace(/%u|%U/g, doman)
  openUrl(url, tab, back, incognito, x, type, value)

openUrl = (url, tab, back=false, incognito=false, x=1, type='txt', value='')->
  ### 打开URL ###
  if tab
    ni = tab.index
  if x > 0
    ni++
  if incognito
    # 隐身窗口
    chrome.windows.create(
      url: url
      incognito: true
    )
    return true
  if JU.lsGet('newPage', true)
    chrome.tabs.getAllInWindow(null,(tabs)->
      for t in tabs
        if isCurrent(t.url, url)
          chrome.tabs.update(t.id, {selected: !back})
          showPageAction(t, type, value)
          return
      chrome.tabs.create({url:url, selected: !back, index : ni}, (tab)->
        showPageAction(tab, type, value)
      )
      true
    )
  else
    chrome.tabs.create({url:url, selected: !back, index : ni}, (tab)->
      showPageAction(tab, type, value)
    )
  true

showPageAction = (tab, type, value)->
  ### 根据ID显示弹出选项 ###
  if /http.+|ftp.+/.test(tab.url)
    chrome.tabs.executeScript(tab.id,
      code: "document.head.setAttribute('data-c-m-t','#{type}');"+
      "document.head.setAttribute('data-c-m-v','#{value.replace("'","\\'")}');"
    )

isCurrent = (turl, url)->
  ### 判断是否是当前页面 ###
  if 'options.html' == url
    if turl.indexOf('phlfmkfpmphogkomddckmggcfpmfchpn') > 0
      if turl.indexOf('chrome-extension') == 0 and turl.indexOf(url) > 0
        return true
  url == turl

getType = (t)->
  ### 获取类型 ###
  for type in ['men', 'txt', 'pic', 'lin']
    if t == type[0]
      return type
  'menu'

execute = (id, value, tab, back, incognito)->
  ### 执行特殊命令 id, value, tab, back, incognito, x ###
  noInc = {
    kd: queryKd
    qr: createQR
    qr_pic: createQR
    qr_txt: createQR
    qr_lin: createQR
    qr_decode: qrcode.decode
    tab_close: tabClose
  }
  if id of noInc
    noInc[id](value, tab, back, incognito)
  inc = {
    su: shortenUrlCopy
    su_lin: shortenUrlCopy
    su_pic: shortenUrlCopy
    su_alert: shortenUrlAlert
    su_lin_alert: shortenUrlAlert
    su_pic_alert: shortenUrlAlert
  }
  if id of inc
    inc[id](value, tab, back, incognito)

getCustomUrl = (array, id)->
  for c in array
    if c[0] == id
      return [c[1]]
  []

getAllUrl = (array, id)->
  u = JU.findArray(array, 'c', id)
  if u
    return [u.u]
  []

openTab = (id, type, value, tab, x=1, fg=null)->
  ### 打开tab页面 id,类型,变量,tab,左右###
  back = id in JU.lsGet("#{type}Back", [])
  incognito = id in JU.lsGet("#{type}Incognito", [])
  back = if JU.lsGet("back", false) then !back else back
  back = if fg != null then fg else back
  console.debug 'openTab %s', id

  all = JU.lsGet('all', [])
  urls = getAllUrl(all, id)
  custom = JU.lsGet(type + 'Custom', [])
  urls = urls.concat(getCustomUrl(custom, id))
  group = JU.lsGet(type[0] + 'cGroup', [])
  for g in group
    if g[0] == id
      urls = urls.concat(getCustomUrl(custom, g[1]))
      urls = urls.concat(getAllUrl(all, g[1]))
  for u in urls
    console.debug 'open %s', u
    _gaq.push(['_trackEvent', 'menu', id])
    if /:|.htm/.test(u)
      show(u, value, tab, back, incognito, x, type)
    else
      # 特殊功能，例如QR码等
      execute(u, value, tab, back, incognito, x)
  true

getCi18n = ->
  if 'ci18n' not in window
    code = JU.lsGet('locale', navigator.language.replace('-', '_'))
    if code not in ['en', 'zh_CN', 'zh_TW']
      code = 'en'
    window.ci18n = new JU.I18n(code)
  window.ci18n

menuReset = ->
  ### 重置菜单 ###
  ci18n = getCi18n()
  chrome.contextMenus.removeAll(->
    for type in ['men', 'txt', 'pic', 'lin']
        ### 创建菜单 ###
        select = JU.lsGet(type + 'Select', [])
        if type == 'lin'
          chrome.contextMenus.create(
            "contexts": ['link']
            'type': 'separator'
            'id': 's_' + JU.getId()<commit_msg>fix #25<commit_after>###
# background 后台运行
创建右键菜单，监听菜单刷新事件
###
chrome.contextMenus.onClicked.addListener((info, tab)->
  ### 单击事件 ###
  console.debug 'onClickHandler'
  type = info.menuItemId[0]
  id = info.menuItemId[1..]
  type = getType(type)
  value = getValue(info, tab, type)
  openTab(id, type, value, tab)
)
chrome.runtime.onStartup.addListener(menuReset)
chrome.runtime.onInstalled.addListener(->
  console.debug 'installed'
  all = JU.lsGet('all', [])
  if all.length == 0
    JU.syncFetch('/init.json', (result)->
      JU.lsSet('all', JSON.parse(result))
      _gaq.push(['_trackEvent', 'db', 'ninit'])
    )
  console.debug 'start'
  ci18n = getCi18n()
  if not JU.lsGet('three_run', false)
    i18n = ci18n.getMessage('i18n')
    JU.lsSet('en', true)
    if i18n == 'cn'
      JU.lsSet('zh_CN', true)
      data =
        txtSelect: ['baidu', 'translate', 'zdic', 'amazon', 'taobao']
        picSelect: ['google_pic', 'baidu_pic', 'qr_decode']
        linSelect: ['weibo_lin', 'gmail_lin', 'qr_lin']
        menSelect: ['i_title']
    else if i18n == 'tw'
      JU.lsSet('zh_TW', true)
    else if i18n == 'ru'
      JU.lsSet('ru', true)
    if not data
      data =
        txtSelect: ['bing', 'translate', 'Amazon_com']
        picSelect: ['google_pic', 'su_pic']
        linSelect: ['gmail_lin', 'qr_lin']
        menSelect: ['i_title']
    for key of data
      JU.lsSet(key, JU.lsGet(key, data[key]))
    chrome.tabs.create({url:'options.html', selected: true})
    JU.lsSet('three_run', true)
    _gaq.push(['_trackEvent', 'option', 'init'])
  menuReset()
)

#getUrls = (custom, ids, fun)->
#  ### 根据ids查找URL,返回URL列表 ###
#  for id in ids
#    _gaq.push(['_trackEvent', 'menu', id])
#    findUrl(id, (ur)->
#      fun(ur)
#    )
#    for c in custom
#      if c[0] == id
#        fun(c[1])
getValue = (info, tab, type)->
  ### 根据类型决定参数值 ###
  {
    'men': tab.url
    'txt': info.selectionText
    'pic': info.srcUrl
    'lin': info.linkUrl
  }[type]

show = (url, value, tab, back=false, incognito=false, x=1, type='txt')->
  ### 根据网址、变量打开页面 网址,变量,后台,类型,隐身,tab,左右###
  if /%l|%L/g.test(url)
    url = url.replace(/%l|%L/g, encodeURIComponent(tab.title))
  if /%s|%S/g.test(url)
    url = url.replace(/%s|%S/g, encodeURIComponent(value))
    #u = /%u|%U/g
    #if u.test(url)
    #  u.lastIndex=0
    #  url = url.replace(u, encoden(value))
  if /%g|%G/g.test(url)
    url = url.replace(/%g|%G/g, encodeToGbk(value))
  if /%t|%T/g.test(url)
    url = url.replace(/%t|%T/g, encodeToBig5(value))
  if /%p|%P/g.test(url)
    url = url.replace(/%p|%P/g, encodeURIComponent(readClipboard()))
  if /%u|%U/g.test(url) and tab
    doman = tab.url.split('/')[2]
    url = url.replace(/%u|%U/g, doman)
  openUrl(url, tab, back, incognito, x, type, value)

openUrl = (url, tab, back=false, incognito=false, x=1, type='txt', value='')->
  ### 打开URL ###
  if tab
    ni = tab.index
  if x > 0
    ni++
  if incognito
    # 隐身窗口
    chrome.windows.create(
      url: url
      incognito: true
    )
    return true
  if JU.lsGet('newPage', true)
    chrome.tabs.getAllInWindow(null,(tabs)->
      for t in tabs
        if isCurrent(t.url, url)
          chrome.tabs.update(t.id, {selected: !back})
          showPageAction(t, type, value)
          return
      chrome.tabs.create({url:url, selected: !back, index : ni}, (tab)->
        showPageAction(tab, type, value)
      )
      true
    )
  else
    chrome.tabs.create({url:url, selected: !back, index : ni}, (tab)->
      showPageAction(tab, type, value)
    )
  true

showPageAction = (tab, type, value)->
  ### 根据ID显示弹出选项 ###
  if /http.+|ftp.+/.test(tab.url)
    chrome.tabs.executeScript(tab.id,
      code: "document.head.setAttribute('data-c-m-t','#{type}');"+
      "document.head.setAttribute('data-c-m-v','#{value.replace("'","\\'")}');"
    )

isCurrent = (turl, url)->
  ### 判断是否是当前页面 ###
  if 'options.html' == url
    if turl.indexOf('phlfmkfpmphogkomddckmggcfpmfchpn') > 0
      if turl.indexOf('chrome-extension') == 0 and turl.indexOf(url) > 0
        return true
  url == turl

getType = (t)->
  ### 获取类型 ###
  for type in ['men', 'txt', 'pic', 'lin']
    if t == type[0]
      return type
  'menu'

execute = (id, value, tab, back, incognito)->
  ### 执行特殊命令 id, value, tab, back, incognito, x ###
  noInc = {
    kd: queryKd
    qr: createQR
    qr_pic: createQR
    qr_txt: createQR
    qr_lin: createQR
    qr_decode: qrcode.decode
    tab_close: tabClose
  }
  if id of noInc
    noInc[id](value, tab, back, incognito)
  inc = {
    su: shortenUrlCopy
    su_lin: shortenUrlCopy
    su_pic: shortenUrlCopy
    su_alert: shortenUrlAlert
    su_lin_alert: shortenUrlAlert
    su_pic_alert: shortenUrlAlert
  }
  if id of inc
    inc[id](value, tab, back, incognito)

getCustomUrl = (array, id)->
  for c in array
    if c[0] == id
      return [c[1]]
  []

getAllUrl = (array, id)->
  u = JU.findArray(array, 'c', id)
  if u
    return [u.u]
  []

openTab = (id, type, value, tab, x=1, fg=null)->
  ### 打开tab页面 id,类型,变量,tab,左右###
  back = id in JU.lsGet("#{type}Back", [])
  incognito = id in JU.lsGet("#{type}Incognito", [])
  back = if JU.lsGet("back", false) then !back else back
  back = if fg != null then fg else back
  console.debug 'openTab %s', id

  all = JU.lsGet('all', [])
  urls = getAllUrl(all, id)
  custom = JU.lsGet(type + 'Custom', [])
  urls = urls.concat(getCustomUrl(custom, id))
  group = JU.lsGet(type[0] + 'cGroup', [])
  for g in group
    if g[0] == id
      for gid in g[1]
        urls = urls.concat(getCustomUrl(custom, gid))
        urls = urls.concat(getAllUrl(all, gid))
  for u in urls
    console.debug 'open %s', u
    _gaq.push(['_trackEvent', 'menu', id])
    if /:|.htm/.test(u)
      show(u, value, tab, back, incognito, x, type)
    else
      # 特殊功能，例如QR码等
      execute(u, value, tab, back, incognito, x)
  true

getCi18n = ->
  if 'ci18n' not in window
    code = JU.lsGet('locale', navigator.language.replace('-', '_'))
    if code not in ['en', 'zh_CN', 'zh_TW']
      code = 'en'
    window.ci18n = new JU.I18n(code)
  window.ci18n

menuReset = ->
  ### 重置菜单 ###
  ci18n = getCi18n()
  chrome.contextMenus.removeAll(->
    for type in ['men', 'txt', 'pic', 'lin']
        ### 创建菜单 ###
        select = JU.lsGet(type + 'Select', [])
        if type == 'lin'
          chrome.contextMenus.create(
            "contexts": ['link']
            'type': 'separator'
            'id': 's_' + JU.getId()
{'fraction_non_alphanumeric': 0.18638914873713752, 'fraction_numerical': 0.008185219831618335, 'mean_word_length': 2.8364234449760763, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '228772', 'n_tokens_mistral': 5344, 'n_tokens_neox': 5364, 'n_words': 1100}