open.d (1569B)
1 import xdg.desktop; 2 import xdg.mime; 3 import std.stdio; 4 import std.process; 5 import std.array; 6 import std.regex; 7 import std.algorithm.searching:startsWith; 8 import std.algorithm:splitter; 9 import std.format; 10 11 bool is_file_url_or_path(in char[] uri){ 12 auto r = ctRegex!(`^(\w[\w+-\.]*)://`); 13 if(auto match = uri.matchFirst(r)){ 14 return match[1] == "file"; 15 } 16 else{ 17 return true; 18 } 19 } 20 21 struct Opener{ 22 Mime mime; 23 Database db; 24 25 void init(){ 26 mime.init(); 27 db.init(); 28 } 29 30 31 void open(in char[] file, in char[] mime){ 32 auto ent = db.get(mime); 33 spawnShell(ent.format(file)); 34 } 35 36 void open(in char[] uri){ 37 if(is_file_url_or_path(uri)){ 38 auto file = uri.file_url_to_path(); 39 auto type = mime.file(file); 40 open(file, type); 41 } 42 else{ 43 auto file = uri; 44 auto browsers = environment.get("BROWSER", 45 "x-www-browser:firefox:firefox-bin:iceweasel:seamonkey:" 46 ~"mozilla:epiphany:konqueror:chromium:chromium-browser:" 47 ~"google-chrome:www-browser:links2:elinks:links:lynx:w3m" 48 ); 49 foreach(browser; browsers.splitter(":")){ 50 auto pid = spawnShell(format!(`%s "%s"`)(browser,uri)); 51 if(wait(pid) == 0){ 52 break; 53 } 54 } 55 } 56 } 57 58 } 59 60 void main(string[] args){ 61 Opener o; 62 o.init(); 63 if(args.length<2){ 64 foreach(l; stdin.byLine()){ 65 try{ 66 o.open(l); 67 } 68 catch(Exception e){ 69 stderr.writeln("Could not open ", l, " ", e.msg); 70 } 71 } 72 } 73 else{ 74 //foreach(arg;args[1..$]){ 75 auto arg = args[1..$].join(" "); 76 try{ 77 o.open(arg); 78 } 79 catch(Exception e){ 80 stderr.writeln("Could not open ", arg, " ", e.msg); 81 } 82 //} 83 } 84 }