xref: /haiku/src/bin/open.cpp (revision d3d8b26997fac34a84981e6d2b649521de2cc45a)
1 /*
2  * Copyright 2003-2005, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 /* Launches an application/document from the shell */
7 
8 
9 #include <Roster.h>
10 #include <Entry.h>
11 #include <String.h>
12 #include <List.h>
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <errno.h>
18 
19 
20 const char *kTrackerSignature = "application/x-vnd.Be-TRAK";
21 
22 
23 int
24 main(int argc, char **argv)
25 {
26 	const char *openWith = kTrackerSignature;
27 	int exitcode = EXIT_SUCCESS;
28 
29 	char *progName = argv[0];
30 	if (strrchr(progName, '/'))
31 		progName = strrchr(progName, '/') + 1;
32 
33 	if (argc < 2)
34 		fprintf(stderr,"usage: %s <file or url or application signature> ...\n", progName);
35 
36 	BRoster roster;
37 
38 	while (*++argv) {
39 		status_t status = B_OK;
40 		argc--;
41 
42 		BEntry entry(*argv);
43 		if ((status = entry.InitCheck()) == B_OK && entry.Exists()) {
44 			entry_ref ref;
45 			entry.GetRef(&ref);
46 
47 			BMessenger target(openWith);
48 			if (target.IsValid()) {
49 				BMessage message(B_REFS_RECEIVED);
50 				message.AddRef("refs", &ref);
51 				// tell the app to open the file
52 				status = target.SendMessage(&message);
53 			} else
54 				status = roster.Launch(&ref);
55 		} else if (!strncasecmp("application/", *argv, 12)) {
56 			// maybe it's an application-mimetype?
57 
58 			// subsequent files are open with that app
59 			openWith = *argv;
60 			// clear possible ENOENT from above
61 			status = B_OK;
62 
63 			// in the case the app is already started,
64 			// don't start it twice if we have other args
65 			BList teams;
66 			if (argc > 1)
67 				roster.GetAppList(*argv, &teams);
68 
69 			if (teams.IsEmpty())
70 				status = roster.Launch(*argv);
71 		} else if (strchr(*argv, ':')) {
72 			// try to open it as an URI
73 			BString mimeType = "application/x-vnd.Be.URL.";
74 			BString arg(*argv);
75 			if (arg.FindFirst("://") >= 0)
76 				mimeType.Append(arg, arg.FindFirst("://"));
77 			else
78 				mimeType.Append(arg, arg.FindFirst(":"));
79 
80 			char *args[2] = { *argv, NULL };
81 			status = roster.Launch(mimeType.String(), 1, args);
82 		} else
83 			status = B_ENTRY_NOT_FOUND;
84 
85 		if (status != B_OK && status != B_ALREADY_RUNNING) {
86 			fprintf(stderr, "%s: \"%s\": %s\n", progName, *argv, strerror(status));
87 			// make sure the shell knows this
88 			exitcode = EXIT_FAILURE;
89 		}
90 	}
91 
92 	return exitcode;
93 }
94