| 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
 | Utils =
  getCurrentVersion: ->
    chrome.runtime.getManifest().version
  # Takes a dot-notation object string and call the function
  # that it points to with the correct value for 'this'.
  invokeCommandString: (str, argArray) ->
    components = str.split('.')
    obj = window
    for component in components[0...-1]
      obj = obj[component]
    func = obj[components.pop()]
    func.apply(obj, argArray)
  # Creates a single DOM element from :html
  createElementFromHtml: (html) ->
    tmp = document.createElement("div")
    tmp.innerHTML = html
    tmp.firstChild
  escapeHtml: (string) -> string.replace(/</g, "<").replace(/>/g, ">")
  # Generates a unique ID
  createUniqueId: do ->
    id = 0
    -> id += 1
  hasChromePrefix: do ->
    chromePrefixes = [ "about:", "view-source:", "extension:", "chrome-extension:", "data:" ]
    (url) ->
      for prefix in chromePrefixes
        return true if url.startsWith prefix
      false
  hasJavascriptPrefix: (url) ->
    url.startsWith "javascript:"
  hasFullUrlPrefix: do ->
    urlPrefix = new RegExp "^[a-z]{3,}://."
    (url) -> urlPrefix.test url
  # Completes a partial URL (without scheme)
  createFullUrl: (partialUrl) ->
    if @hasFullUrlPrefix(partialUrl) then partialUrl else ("http://" + partialUrl)
  # Tries to detect if :str is a valid URL.
  isUrl: (str) ->
    # Must not contain spaces
    return false if ' ' in str
    # Starts with a scheme: URL
    return true if @hasFullUrlPrefix str
    # More or less RFC compliant URL host part parsing. This should be sufficient for our needs
    urlRegex = new RegExp(
      '^(?:([^:]+)(?::([^:]+))?@)?' + # user:password (optional) => \1, \2
      '([^:]+|\\[[^\\]]+\\])'       + # host name (IPv6 addresses in square brackets allowed) => \3
      '(?::(\\d+))?$'                 # port number (optional) => \4
      )
    # Official ASCII TLDs that are longer than 3 characters + inofficial .onion TLD used by TOR
    longTlds = ['arpa', 'asia', 'coop', 'info', 'jobs', 'local', 'mobi', 'museum', 'name', 'onion']
    specialHostNames = ['localhost']
    # Try to parse the URL into its meaningful parts. If matching fails we're pretty sure that we don't have
    # some kind of URL here.
    match = urlRegex.exec (str.split '/')[0]
    return false unless match
    hostName = match[3]
    # Allow known special host names
    return true if hostName in specialHostNames
    # Allow IPv6 addresses (need to be wrapped in brackets as required by RFC). It is sufficient to check for
    # a colon, as the regex wouldn't match colons in the host name unless it's an v6 address
    return true if ':' in hostName
    # At this point we have to make a decision. As a heuristic, we check if the input has dots in it. If yes,
    # and if the last part could be a TLD, treat it as an URL
    dottedParts = hostName.split '.'
    if dottedParts.length > 1
      lastPart = dottedParts.pop()
      return true if 2 <= lastPart.length <= 3 or lastPart in longTlds
    # Allow IPv4 addresses
    return true if /^(\d{1,3}\.){3}\d{1,3}$/.test hostName
    # Fallback: no URL
    return false
  # Map a search query to its URL encoded form. The query may be either a string or an array of strings.
  # E.g. "BBC Sport" -> "BBC+Sport".
  createSearchQuery: (query) ->
    query = query.split(/\s+/) if typeof(query) == "string"
    query.map(encodeURIComponent).join "+"
  # Create a search URL from the given :query (using either the provided search URL, or the default one).
  # It would be better to pull the default search engine from chrome itself.  However, chrome does not provide
  # an API for doing so.
  createSearchUrl: (query, searchUrl = Settings.get("searchUrl")) ->
    searchUrl += "%s" unless 0 <= searchUrl.indexOf "%s"
    searchUrl.replace /%s/g, @createSearchQuery query
  # Converts :string into a Google search if it's not already a URL. We don't bother with escaping characters
  # as Chrome will do that for us.
  convertToUrl: (string) ->
    string = string.trim()
    # Special-case about:[url], view-source:[url] and the like
    if Utils.hasChromePrefix string
      string
    else if Utils.hasJavascriptPrefix string
      # We blindly URL decode javascript: URLs.  That's what Chrome does when they're clicked, or entered into
      # the omnibox.  However, Chrome does not URL decode such URLs in chrome.tabs.update.
      # This is arguably a Chrome bug.  See https://code.google.com/p/chromium/issues/detail?id=483000.
      decodeURI string
    else if Utils.isUrl string
      Utils.createFullUrl string
    else
      Utils.createSearchUrl string
  # detects both literals and dynamically created strings
  isString: (obj) -> typeof obj == 'string' or obj instanceof String
  # Transform "zjkjkabz" into "abjkz".
  distinctCharacters: (str) ->
    unique = ""
    for char in str.split("").sort()
      unique += char unless 0 <= unique.indexOf char
    unique
  # Compares two version strings (e.g. "1.1" and "1.5") and returns
  # -1 if versionA is < versionB, 0 if they're equal, and 1 if versionA is > versionB.
  compareVersions: (versionA, versionB) ->
    versionA = versionA.split(".")
    versionB = versionB.split(".")
    for i in [0...(Math.max(versionA.length, versionB.length))]
      a = parseInt(versionA[i] || 0, 10)
      b = parseInt(versionB[i] || 0, 10)
      if (a < b)
        return -1
      else if (a > b)
        return 1
    0
  # True if the current Chrome version is at least the required version.
  haveChromeVersion: (required) ->
    chromeVersion = navigator.appVersion.match(/Chrome\/(.*?) /)?[1]
    chromeVersion and 0 <= Utils.compareVersions chromeVersion, required
  # Zip two (or more) arrays:
  #   - Utils.zip([ [a,b], [1,2] ]) returns [ [a,1], [b,2] ]
  #   - Length of result is `arrays[0].length`.
  #   - Adapted from: http://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function
  zip: (arrays) ->
    arrays[0].map (_,i) ->
      arrays.map( (array) -> array[i] )
  # locale-sensitive uppercase detection
  hasUpperCase: (s) -> s.toLowerCase() != s
  # Give objects (including elements) distinct identities.
  getIdentity: do ->
    identities = []
    (obj) ->
      index = identities.indexOf obj
      if index < 0
        index = identities.length
        identities.push obj
      "identity-" + index
  # Return a copy of object, but with some of its properties omitted.
  copyObjectOmittingProperties: (obj, properties...) ->
    obj = extend {}, obj
    delete obj[property] for property in properties
    obj
  # Does string match any of these regexps?
  matchesAnyRegexp: (regexps, string) ->
    for re in regexps
      return true if re.test string
    false
  # Convenience wrapper for setTimeout (with the arguments around the other way).
  setTimeout: (ms, func) -> setTimeout func, ms
  # Like Nodejs's nextTick.
  nextTick: (func) -> @setTimeout 0, func
# This creates a new function out of an existing function, where the new function takes fewer arguments. This
# allows us to pass around functions instead of functions + a partial list of arguments.
Function::curry = ->
  fixedArguments = Array.copy(arguments)
  fn = this
  -> fn.apply(this, fixedArguments.concat(Array.copy(arguments)))
Array.copy = (array) -> Array.prototype.slice.call(array, 0)
String::startsWith = (str) -> @indexOf(str) == 0
String::ltrim = -> @replace /^\s+/, ""
String::rtrim = -> @replace /\s+$/, ""
globalRoot = window ? global
globalRoot.extend = (hash1, hash2) ->
  for key of hash2
    hash1[key] = hash2[key]
  hash1
# A simple cache. Entries used within two expiry periods are retained, otherwise they are discarded.
# At most 2 * @entries entries are retained.
class SimpleCache
  # expiry: expiry time in milliseconds (default, one hour)
  # entries: maximum number of entries in @cache (there may be this many entries in @previous, too)
  constructor: (@expiry = 60 * 60 * 1000, @entries = 1000) ->
    @cache = {}
    @rotate() # Force start the rotation timer.
  rotate: ->
    @previous = @cache
    @cache = {}
    # We reset the timer every time the cache is rotated (which could be because a previous timer expired, or
    # because the number of @entries was exceeded.
    clearTimeout @timer if @timer?
    @timer = Utils.setTimeout @expiry, => @rotate()
  has: (key) ->
    (key of @cache) or key of @previous
  get: (key) ->
    if key of @cache
      @cache[key]
    else if key of @previous
      @cache[key] = @previous[key]
    else
      null
  clear: ->
    @rotate()
    @rotate()
  # Because of the timer, we can't just let these caches go out of scope and have the garbage collector
  # harvest them.  Whenever they may fall out of use, we need to remove the timer. @rotate() can be used to
  # restart the cache.
  suspend: ->
    clearTimeout @timer if @timer?
    @timer = null
  # Set value, and return that value.  If value is null, then delete key.
  set: (key, value = null) ->
    if value?
      @cache[key] = value
      delete @previous[key]
      @rotate() if @entries < Object.keys(@cache).length
    else
      delete @cache[key]
      delete @previous[key]
    value
# This is a simple class for the common case where we want to use some data value which may be immediately
# available, or we may have to wait.  It implements the use-immediately-or-wait queue, and calls the function
# to fetch the data asynchronously.
class AsyncDataFetcher
  constructor: (fetch) ->
    @data = null
    @queue = []
    fetch (@data) =>
      Utils.nextTick =>
        callback @data for callback in @queue
        @queue = null
  use: (callback) ->
    if @data? then callback @data else @queue.push callback
root = exports ? window
root.Utils = Utils
root.SimpleCache = SimpleCache
root.AsyncDataFetcher = AsyncDataFetcher
 |