Class: HookApp

Inherits:
Object
  • Object
show all
Includes:
Hook::Prompt
Defined in:
lib/hook/hookapp.rb

Overview

Hook.app functions

Direct Known Subclasses

Hooker

Instance Method Summary collapse

Methods included from Hook::PromptFZF

#fzf, #install_fzf, #uninstall_fzf, #which_fzf

Methods included from Hook::PromptSTD

#clear_screen, #restore_std, #silence_std

Instance Method Details

#act_on(url) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/hook/hookapp.rb', line 294

def act_on(url)
  menu_items = ['Open in default app']
  return open_linked(url) unless File.exist?(url)

  marks = get_hooks(url)
  menu_items << 'Browse file' if marks.count.positive?

  args = ['--prompt="Choose action > "',
          '--layout=reverse-list',
          '--height=60%',
          "--min-height=#{menu_items.count + 1}"]
  sel = `echo #{Shellwords.escape(menu_items.join("\n"))} | '#{fzf}' #{args.join(' ')}`.chomp
  return if sel.nil? || sel.empty?

  case sel
  when /Browse file/
    browse_linked(url)
  else
    `open '#{url}'`
  end
end

#all_bookmarksObject

Get all known bookmarks. Return array of bookmark hashes.



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/hook/hookapp.rb', line 142

def all_bookmarks
  `osascript <<'APPLESCRIPT'
    tell application "#{HOOK_APP}"
      set _marks to every bookmark
      set _out to {}
      repeat with _hook in _marks
        set _out to _out & (name of _hook & "||" & address of _hook & "||" & path of _hook)
      end repeat
      set {astid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "^^"}
      set _output to _out as string
      set AppleScript's text item delimiters to astid
      return _output
    end tell
  APPLESCRIPT`.strip.split_hooks
end

#bookmark_for(url) ⇒ Object

Get a Hook bookmark for file or URL. Return bookmark hash.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hook/hookapp.rb', line 34

def bookmark_for(url)
  url.valid_hook!
  raise "Invalid target: #{url}" unless url

  begin
    mark = `osascript <<'APPLESCRIPT'
      tell application "#{HOOK_APP}"
        set _hook to make bookmark with data "#{url}"
        if _hook is missing value
          return ""
        else
          return name of _hook & "||" & address of _hook & "||" & path of _hook
        end if
      end tell
    APPLESCRIPT`.strip
  rescue p => e
    raise e
  end

  raise "Error getting bookmark for #{url}" if mark.empty?
  mark.split_hook
end

#bookmark_from_app(app, opts) ⇒ Object

Get a bookmark from the foreground document of specified app.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/hook/hookapp.rb', line 83

def bookmark_from_app(app, opts)
  mark = `osascript <<'APPLESCRIPT'
    tell application "System Events" to set front_app to name of first application process whose frontmost is true
    tell application "#{app}" to activate
    delay 2
    tell application "#{HOOK_APP}"
      set _hook to (bookmark from active window)
      set _output to (name of _hook & "||" & address of _hook & "||" & path of _hook)
    end tell
    tell application front_app to activate
    return _output
  APPLESCRIPT`.strip.split_hook
  title = mark[:name].empty? ? "#{app.cap} link" : mark[:name]
  output = opts[:markdown] ? "[#{title}](#{mark[:url]})" : mark[:url]

  if opts[:copy]
    "Copied Markdown link for '#{title}' to clipboard" if output.clip
  else
    output
  end
end

#browse_bookmarks(glob) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/hook/hookapp.rb', line 260

def browse_bookmarks(glob)
  glob_all = '**/*'
  root = if glob.is_a?(Array)
           glob.count.positive? ? glob : Dir.glob(glob_all)
         elsif glob && File.exist?(glob)
           hooks = get_hooks(glob)
           return select_hook(hooks) unless hooks.empty? || File.directory?(glob)

           Dir.glob([File.expand_path(glob), glob_all])
         else
           Dir.glob(glob.nil? || glob.empty? ? glob_all : glob)
         end

  args = ['--layout=reverse-list',
          '--header="esc: cancel, return: browse"',
          '--prompt="  Select file > "',
          %(--preview='hook ls -o m {}'),
          '--height=60%',
          '--min-height=10']

  sel = `echo #{Shellwords.escape(root.join("\n"))} | '#{fzf}' #{args.join(' ')}`.chomp.split("\n")

  if sel.count == 1
    marks = get_hooks(sel[0])
    if marks.count.positive?
      browse_linked(sel[0])
    else
      browse_bookmarks(glob)
    end
  else
    open_linked(sel)
  end
end

#browse_linked(url) ⇒ Object

Select from a menu of available hooks and open using macOS ‘open`.



344
345
346
347
348
349
350
351
352
353
354
# File 'lib/hook/hookapp.rb', line 344

def browse_linked(url)
  marks = get_hooks(url)
  if marks.empty?
    warn "No hooks found for #{url}"
  else
    res = select_hook(marks)
    unless res.empty?
      res.each { |mark| mark[:path] ? act_on(mark[:path]) : `open '#{mark[:url]}'` }
    end
  end
end

#clip_bookmark(url, opts) ⇒ Object

Create a bookmark for specified file/url and copy to the clipboard.



183
184
185
186
# File 'lib/hook/hookapp.rb', line 183

def clip_bookmark(url, opts)
  mark = bookmark_for(url)
  copy_bookmark(mark[:name], mark[:url], opts)
end

#clone_hooks(args) ⇒ Object

Copy all hooks from source file to target file



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/hook/hookapp.rb', line 380

def clone_hooks(args)
  target = args.pop.valid_hook
  source = args[0].valid_hook

  if target && source
    hooks = get_hooks(source)
    hooks.each do |hook|
      `osascript <<'APPLESCRIPT'
        tell application "#{HOOK_APP}"
          set _mark1 to make bookmark with data "#{hook[:url]}"
          set _mark2 to make bookmark with data "#{target}"
          hook _mark1 and _mark2
          return true
        end tell
      APPLESCRIPT`
    end
    "Hooks from #{source} cloned to #{target}"
  else
    raise 'Invalid file specified'
  end
end

#copy_bookmark(title, url, opts) ⇒ Object

Create a bookmark from specified title and url and copy to the clipboard.



189
190
191
192
193
194
195
# File 'lib/hook/hookapp.rb', line 189

def copy_bookmark(title, url, opts)
  raise "No URL found" if url.empty?
  title = title.empty? ? 'No title' : title
  output = opts[:markdown] ? "[#{title}](#{url})" : url
  output.clip
  %(Copied #{opts[:markdown] ? 'Markdown link' : 'Hook URL'} for '#{title}' to clipboard)
end

#decode(string) ⇒ Object



566
567
568
569
570
571
572
573
# File 'lib/hook/hookapp.rb', line 566

def decode(string)
  result = `osascript <<'APPLESCRIPT'
tell application "#{HOOK_APP}"
percent decode "#{string.escape_quotes}"
end tell
APPLESCRIPT`.strip
  print result
end

#delete_all_hooks(url, force: false) ⇒ Object

Delete all hooked files/urls from target file



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/hook/hookapp.rb', line 403

def delete_all_hooks(url, force: false)
  unless force
    STDERR.print "Are you sure you want to delete ALL hooks from #{url} (y/N)? "
    res = STDIN.gets.strip
  end

  if res =~ /^y/i || force
    get_hooks(url).each do |hook|
      `osascript <<'APPLESCRIPT'
        tell application "#{HOOK_APP}"
          set _mark1 to make bookmark with data "#{hook[:url]}"
          set _mark2 to make bookmark with data "#{url}"
          unhook _mark1 and _mark2
          return true
        end tell
      APPLESCRIPT`
    end
    "Removed all hooks from #{url}"
  end
end

#delete_hooks(args, opts) ⇒ Object

Delete hooks between two files/urls



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/hook/hookapp.rb', line 425

def delete_hooks(args, opts)
  urls = args.map(&:valid_hook).delete_if { |url| !url }
  output = []
  if opts[:all]
    urls.each_with_index do |url, i|
      raise "Invalid target: #{args[i]}" unless url

      output.push(delete_all_hooks(url, force: opts[:force]))
    end
    return output.join("\n")
  end

  if urls.length == 2
    source = urls[0]
    target = urls[1]
    `osascript <<'APPLESCRIPT'
      tell application "#{HOOK_APP}"
        set _mark1 to make bookmark with data "#{source}"
        set _mark2 to make bookmark with data "#{target}"
        unhook _mark1 and _mark2
        return true
      end tell
    APPLESCRIPT`
    "Hook removed between #{source} and #{target}"
  else
    raise 'Invalid number of URLs or files specified'
  end
end

#encode(string) ⇒ Object



557
558
559
560
561
562
563
564
# File 'lib/hook/hookapp.rb', line 557

def encode(string)
  result = `osascript <<'APPLESCRIPT'
tell application "#{HOOK_APP}"
percent encode "#{string.escape_quotes}"
end tell
APPLESCRIPT`.strip.gsub(/'/,'%27')
  print result
end

#format_regex(options) ⇒ Object

Create a single regex for validation of an array by first char or full match.



11
12
13
14
15
# File 'lib/hook/hookapp.rb', line 11

def format_regex(options)
  fmt_rx_array = []
  options.map {|fmt| fmt_rx_array.push(fmt.sub(/^(.)(.*?)$/, '\1(\2)?')) }
  Regexp.new("^(#{fmt_rx_array.join('|')})$",'i')
end

#get_hooks(url) ⇒ Object

Get bookmarks hooked to file or URL. Return array of bookmark hashes.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/hook/hookapp.rb', line 58

def get_hooks(url)
  url.valid_hook!
  raise "Invalid target: #{url}" unless url

  hooks = `osascript <<'APPLESCRIPT'
    tell application "#{HOOK_APP}"
      set _mark to make bookmark with data "#{url}"
      if _mark is missing value
        return ""
      end if
      set _hooks to hooked bookmarks of _mark
      set _out to {}
      repeat with _hook in _hooks
        set _out to _out & (name of _hook & "||" & address of _hook & "||" & path of _hook)
      end repeat
      set {astid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "^^"}
      set _output to _out as string
      set AppleScript's text item delimiters to astid
      return _output
    end tell
  APPLESCRIPT`.strip
  hooks.split_hooks
end

Create bi-directional links between every file/url in the list of arguments



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/hook/hookapp.rb', line 455

def link_all(args)
  args.each do |file|
    source = file.valid_hook
    link_to = args.dup.map(&:valid_hook).reject { |url| url == source }
    link_to.each do |url|
      `osascript <<'APPLESCRIPT'
        tell application "#{HOOK_APP}"
          set _mark1 to make bookmark with data "#{source}"
          set _mark2 to make bookmark with data "#{url}"
          hook _mark1 and _mark2
          return true
        end tell
      APPLESCRIPT`
    end
  end
  "Linked #{args.length} files to each other"
end

Link 2 or more files/urls with bi-directional hooks.



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/hook/hookapp.rb', line 357

def link_files(args)
  target = args.pop
  target.valid_hook!
  raise "Invalid target: #{target}" unless target

  args.each do |file|
    file.valid_hook!
    raise "Invalid target: #{file}" unless file

    puts "Linking #{file} and #{target}..."
    `osascript <<'APPLESCRIPT'
      tell application "#{HOOK_APP}"
        set _mark1 to make bookmark with data "#{file}"
        set _mark2 to make bookmark with data "#{target}"
        hook _mark1 and _mark2
        return true
      end tell
    APPLESCRIPT`
  end
  "Linked #{args.length} files to #{target}"
end

#linked_bookmarks(args, opts) ⇒ Object

Get a list of all hooks on a file/url.



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/hook/hookapp.rb', line 474

def linked_bookmarks(args, opts)
  result = []

  separator = args.length == 1 && opts[:format] == 'paths' && opts[:null_separator] ? "\0" : "\n"

  if args.nil? || args.empty?
    result = output_array(all_bookmarks, opts)
  else
    args.each do |url|
      source_mark = bookmark_for(url)
      filename = source_mark[:name]

      case opts[:format]
      when /^m/
        filename = "[#{source_mark[:name]}](#{source_mark[:url]})"
        filename += " <file://#{CGI.escape(source_mark[:path])}>" if source_mark[:path]
      when /^p/
        filename = "File: #{source_mark[:name]}"
        filename += " (#{source_mark[:path]})" if source_mark[:path]
      when /^h/
        filename = "File: #{source_mark[:name]}"
        filename += " (#{source_mark[:url]})" if source_mark[:url]
      else
        filename = "Bookmarks attached to #{source_mark[:path] || source_mark[:url]}"
      end

      hooks_arr = get_hooks(url)

      output = output_array(hooks_arr, opts)
      result.push({ file: filename, links: output.join(separator) }) if output
    end


    if result.length > 1 || opts[:format] == 'verbose'
      result.map! do |res|
        "#{res[:file]}\n\n#{res[:links]}\n"
      end
    else
      result.map! do |res|
        res[:links]
      end
    end
  end
  result.join(separator)
end

#open_gui(url) ⇒ Object

Open the Hook GUI for browsing/performing actions on a file or url



317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/hook/hookapp.rb', line 317

def open_gui(url)
  result = `osascript <<'APPLESCRIPT'
  tell application "#{HOOK_APP}"
    set _mark to make bookmark with data "#{url.valid_hook}"
    if _mark is missing value
      return "Failed to create bookmark for #{url}"
    else
      invoke on _mark
      return ""
    end if
  end tell
  APPLESCRIPT`.strip
  raise result unless result.empty?
end

#open_linked(url) ⇒ Object

Select from a menu of available hooks and open using macOS ‘open`.



333
334
335
336
337
338
339
340
341
# File 'lib/hook/hookapp.rb', line 333

def open_linked(url)
  marks = get_hooks(url)
  if marks.empty?
    warn "No hooks found for #{url}"
  else
    res = select_hook(marks)
    res.each { |mark| `open '#{mark[:url]}'` } unless res.empty?
  end
end

#output_array(hooks_arr, opts) ⇒ Object

Output an array of hooks in the given format.



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/hook/hookapp.rb', line 521

def output_array(hooks_arr, opts)
  if !hooks_arr.empty?
    hooks_arr.reject! { |h| h[:path].nil? || h[:path] == '' } if opts[:files_only]

    output = []

    case opts[:format]
    when /^m/
      hooks_arr.each do |h|
        if h[:name].empty?
          title = h[:url]
        else
          title = h[:name]
        end
        output.push("- [#{title}](#{h[:url]})")
      end
    when /^p/
      hooks_arr.each do |h|
        output.push(h[:path].nil? ? h[:url] : h[:path])
      end
    when /^h/
      hooks_arr.each do |h|
        output.push(h[:url])
      end
    else
      hooks_arr.each do |h|
        output.push("Title: #{h[:name]}\nPath: #{h[:path]}\nAddress: #{h[:url]}\n---------------------")
      end
    end
  else
    warn 'No bookmarks'
  end

  output
end

#search_bookmarks(search, opts) ⇒ Object

Search bookmarks, using both names and addresses unless options contain “:names_only”. Return results as formatted list.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/hook/hookapp.rb', line 160

def search_bookmarks(search, opts)
  unless search.nil? || search.empty?
    result = search_name(search)
    unless opts[:names_only]
      more_results = search_path_or_address(search)
      result = result.concat(more_results).uniq
    end
  else
    result = all_bookmarks
  end

  separator = opts[:format] == 'paths' && opts[:null_separator] ? "\0" : "\n"

  output = output_array(result, opts)

  if opts[:format] =~ /^v/
    "Search results for: #{search}\n---------\n" + output.join("\n") if output
  else
    output.join(separator) if output
  end
end

#search_name(search) ⇒ Object

Search boomark names/titles. Return array of bookmark hashes.



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/hook/hookapp.rb', line 106

def search_name(search)
  `osascript <<'APPLESCRIPT'
    set searchString to "#{search.strip}"
    tell application "#{HOOK_APP}"
      set _marks to every bookmark whose name contains searchString
      set _out to {}
      repeat with _hook in _marks
        set _out to _out & (name of _hook & "||" & address of _hook & "||" & path of _hook)
      end repeat
      set {astid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "^^"}
      set _output to _out as string
      set AppleScript's text item delimiters to astid
      return _output
    end tell
  APPLESCRIPT`.strip.split_hooks
end

#search_path_or_address(search) ⇒ Object

Search bookmark paths and addresses. Return array of bookmark hashes.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/hook/hookapp.rb', line 124

def search_path_or_address(search)
  `osascript <<'APPLESCRIPT'
    set searchString to "#{search.strip}"
    tell application "#{HOOK_APP}"
      set _marks to every bookmark whose path contains searchString or address contains searchString
      set _out to {}
      repeat with _hook in _marks
        set _out to _out & (name of _hook & "||" & address of _hook & "||" & path of _hook)
      end repeat
      set {astid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "^^"}
      set _output to _out as string
      set AppleScript's text item delimiters to astid
      return _output
    end tell
  APPLESCRIPT`.strip.split_hooks
end

#select_hook(marks) ⇒ Object

Generate a menu of available hooks for selecting one or more hooks to operate on. Revamped to use ‘fzf`, which is embedded as `lib/helpers/fuzzyfilefinder` to avoid any conflicts. Allows multiple selections with tab key, and type-ahead fuzzy filtering of results.



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
# File 'lib/hook/hookapp.rb', line 200

def select_hook(marks)
  # intpad = marks.length.to_s.length + 1
  # marks.each_with_index do |mark, i|
  #   STDERR.printf "%#{intpad}d) %s\n", i + 1, mark[:name]
  # end
  # STDERR.print 'Open which bookmark: '
  # sel = STDIN.gets.strip.to_i
  # raise 'Invalid selection' unless sel.positive? && sel <= marks.length

  # marks[sel - 1]

  options = marks.map do |mark|
    if mark[:name]
      id = mark[:name]
    elsif mark[:path]
      id = mark[:path]
    elsif mark[:url]
      id = mark[:url]
    else
      return false
    end

    if mark[:path]
      loc = File.dirname(mark[:path])
    elsif mark[:url]
      url = URI.parse(mark[:url])
      id = mark[:url]
      loc = "#{url.scheme} + ' - ' + url.hostname"
    else
      loc = ''
    end

    "#{id}\t#{mark[:path]}\t#{mark[:url]}\t#{loc}"
  end

  options.delete_if(&:!)

  raise 'Error processing available hooks' if options.empty?

  args = ['--layout=reverse-list',
          '--header="esc: cancel, tab: multi-select, ctrl-a: select all, return: open"',
          '--bind ctrl-a:select-all',
          '--prompt="  Select hooks > "',
          '--multi',
          '--tabstop=4',
          '--delimiter="\t"',
          '--with-nth=1,4',
          '--height=60%',
          '--min-height=10']

  sel = `echo #{Shellwords.escape(options.join("\n"))} | '#{fzf}' #{args.join(' ')}`.chomp

  res = sel.split(/\n/).map do |s|
    ps = s.split(/\t/)
    { name: ps[0], path: ps[1], url: ps[2] }
  end

  res || []
end

#validate_format(fmt, options) ⇒ Object

Check if format fully matches or matches the first character of available options. Return full valid format or nil



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/hook/hookapp.rb', line 20

def validate_format(fmt, options)
  valid_format_rx = options.map { |format| format.sub(/^(.)(.*)$/, '^\1(\2)?$') }
  valid_format = nil
  valid_format_rx.each_with_index do |rx, i|
    cmp = Regexp.new(rx, 'i')
    next unless fmt =~ cmp

    valid_format = options[i]
    break
  end
  valid_format
end