browsers.nim 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple proc for opening URLs with the user's
  10. ## default browser.
  11. import strutils
  12. when defined(windows):
  13. import winlean
  14. else:
  15. import os, osproc
  16. proc openDefaultBrowser*(url: string) =
  17. ## opens `url` with the user's default browser. This does not block.
  18. ##
  19. ## Under Windows, ``ShellExecute`` is used. Under Mac OS X the ``open``
  20. ## command is used. Under Unix, it is checked if ``gnome-open`` exists and
  21. ## used if it does. Next attempt is ``kde-open``, then ``xdg-open``.
  22. ## Otherwise the environment variable ``BROWSER`` is used to determine the
  23. ## default browser to use.
  24. when defined(windows):
  25. when useWinUnicode:
  26. var o = newWideCString("open")
  27. var u = newWideCString(url)
  28. discard shellExecuteW(0'i32, o, u, nil, nil, SW_SHOWNORMAL)
  29. else:
  30. discard shellExecuteA(0'i32, "open", url, nil, nil, SW_SHOWNORMAL)
  31. elif defined(macosx):
  32. discard execShellCmd("open " & quoteShell(url))
  33. else:
  34. const attempts = ["gnome-open ", "kde-open ", "xdg-open "]
  35. var u = quoteShell(url)
  36. for a in items(attempts):
  37. if execShellCmd(a & u) == 0: return
  38. for b in getEnv("BROWSER").string.split(PathSep):
  39. try:
  40. # we use ``startProcess`` here because we don't want to block!
  41. discard startProcess(command=b, args=[url], options={poUsePath})
  42. return
  43. except OSError:
  44. discard