browsers.nim 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. ##
  12. ## Unstable API.
  13. import strutils
  14. when defined(windows):
  15. import winlean
  16. from os import absolutePath
  17. else:
  18. import os, osproc
  19. const osOpenCmd* =
  20. when defined(macos) or defined(macosx) or defined(windows): "open" else: "xdg-open" ## \
  21. ## Alias for the operating system specific *"open"* command,
  22. ## ``"open"`` on OSX, MacOS and Windows, ``"xdg-open"`` on Linux, BSD, etc.
  23. proc prepare(s: string): string =
  24. if s.contains("://"):
  25. result = s
  26. else:
  27. result = "file://" & absolutePath(s)
  28. proc openDefaultBrowser*(url: string) =
  29. ## opens `url` with the user's default browser. This does not block.
  30. ##
  31. ## Under Windows, ``ShellExecute`` is used. Under Mac OS X the ``open``
  32. ## command is used. Under Unix, it is checked if ``xdg-open`` exists and
  33. ## used if it does. Otherwise the environment variable ``BROWSER`` is
  34. ## used to determine the default browser to use.
  35. ##
  36. ## This proc doesn't raise an exception on error, beware.
  37. when defined(windows):
  38. var o = newWideCString(osOpenCmd)
  39. var u = newWideCString(prepare url)
  40. discard shellExecuteW(0'i32, o, u, nil, nil, SW_SHOWNORMAL)
  41. elif defined(macosx):
  42. discard execShellCmd(osOpenCmd & " " & quoteShell(prepare url))
  43. else:
  44. var u = quoteShell(prepare url)
  45. if execShellCmd(osOpenCmd & " " & u) == 0: return
  46. for b in getEnv("BROWSER").string.split(PathSep):
  47. try:
  48. # we use ``startProcess`` here because we don't want to block!
  49. discard startProcess(command = b, args = [url], options = {poUsePath})
  50. return
  51. except OSError:
  52. discard