1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "nsCommandLineServiceMac.h"
10 #include "MacApplicationDelegate.h"
12 #include <Cocoa/Cocoa.h>
14 namespace CommandLineServiceMac {
16 static const int kArgsGrowSize = 20;
18 static char** sArgs = nullptr;
19 static int sArgsAllocated = 0;
20 static int sArgsUsed = 0;
22 void AddToCommandLine(const char* inArgText) {
23 if (sArgsUsed >= sArgsAllocated - 1) {
24 // realloc does not free the given pointer if allocation fails
25 char** temp = static_cast<char**>(
26 realloc(sArgs, (sArgsAllocated + kArgsGrowSize) * sizeof(char*)));
29 sArgsAllocated += kArgsGrowSize;
32 char* temp2 = strdup(inArgText);
35 sArgs[sArgsUsed++] = temp2;
36 sArgs[sArgsUsed] = nullptr;
41 // Caller has ownership of argv and is responsible for freeing the allocated
43 void SetupMacCommandLine(int& argc, char**& argv, bool forRestart) {
44 sArgs = static_cast<char**>(malloc(kArgsGrowSize * sizeof(char*)));
46 sArgsAllocated = kArgsGrowSize;
50 // Copy args, stripping anything we don't want.
51 for (int arg = 0; arg < argc; arg++) {
52 char* flag = argv[arg];
53 // Don't pass on the psn (Process Serial Number) flag from the OS, or
54 // the "-foreground" flag since it will be set below if necessary.
55 if (strncmp(flag, "-psn_", 5) != 0 && strncmp(flag, "-foreground", 11) != 0)
56 AddToCommandLine(flag);
59 // Process the URLs we captured when the NSApp was first run and add them to
61 nsTArray<nsCString> startupURLs = TakeStartupURLs();
62 for (const nsCString& url : startupURLs) {
63 AddToCommandLine("-url");
64 AddToCommandLine(url.get());
67 // If the process will be relaunched, the child should be in the foreground
68 // if the parent is in the foreground. This will be communicated in a
69 // command-line argument to the child.
71 NSRunningApplication* frontApp =
72 [[NSWorkspace sharedWorkspace] frontmostApplication];
73 if ([frontApp isEqual:[NSRunningApplication currentApplication]]) {
74 AddToCommandLine("-foreground");
83 } // namespace CommandLineServiceMac