R/macos_notify.R

Defines functions macos_notify

macos_notify <- function(
    title         = '',
    subtitle      = NA,
    message       = '',
    app_icon      = NA,
    content_image = NA,
    command       = NA,
    open_iterm    = FALSE
  ) {
  # R wrapper for julienXX's terminal-notifier gem found here:
  # https://github.com/julienXX/terminal-notifier
  #
  # Arguments:
  #     title {char} -- title string for notification
  #     subtitle {char} -- subtitle string for notification
  #     message {char} -- message string for notification
  #     app_icon {char} -- path to image file to display instead of application icon
  #     content_image {char} -- path to image file to attach inside of notification
  #     command {char} -- shell command string to execute when notification is clicked
  #     open_iterm {logical} -- overwrites 'command' parameter as 'open /Applications/iTerm.app'
  #
  # Returns:
  #     nothing

  # Check that terminal notifier is installed
  tnv = system("which terminal-notifier", intern = TRUE)
  if (!file.exists(tnv)) {
    stop("terminal-notifier is not installed! Please install it per instructions at https://github.com/julienXX/terminal-notifier")
  }

  # Build list of arguments for terminal-notifier and check that each parameter is valid
  cl_string = c()
  if (!is.na(title)) {
    stopifnot(is.character(title))
    cl_string = append(cl_string, sprintf("-title '%s'", title))
  }
  if (!is.na(subtitle)) {
    stopifnot(is.character(subtitle))
    cl_string = append(cl_string, sprintf("-subtitle '%s'", subtitle))
  }
  if (!is.na(message)) {
    stopifnot(is.character(message))
    cl_string = append(cl_string, sprintf("-message '%s'", message))
  }
  if (!is.na(app_icon)) {
    stopifnot(is.character(app_icon))
    stopifnot(file.exists(app_icon))
    cl_string = append(cl_string, sprintf("-appIcon '%s'", app_icon))
  }
  if (!is.na(content_image)) {
    stopifnot(is.character(content_image))
    stopifnot(file.exists(content_image))
    cl_string = append(cl_string, sprintf("-contentImage '%s'", content_image))
  }
  if (open_iterm) {
    cl_string = append(cl_string, sprintf("-execute '%s'", "open /Applications/iTerm.app"))
  } else if (!is.na(command)) {
    stopifnot(is.character(command))
    cl_string = append(cl_string, sprintf("-execute '%s'", gsub("\\'", "\\\\'", command)))

  }

  # Build final command and execute
  cmd = sprintf('terminal-notifier %s', paste0(cl_string, collapse = " "))
  system(cmd)
}
tsouchlarakis/rdoni documentation built on Sept. 16, 2019, 8:53 p.m.