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"
7 #include "MacApplicationDelegate.h"
9 namespace CommandLineServiceMac {
11 static const int kArgsGrowSize = 20;
13 static char** sArgs = nullptr;
14 static int sArgsAllocated = 0;
15 static int sArgsUsed = 0;
17 static bool sBuildingCommandLine = false;
19 void AddToCommandLine(const char* inArgText) {
20 if (sArgsUsed >= sArgsAllocated - 1) {
21 // realloc does not free the given pointer if allocation fails
23 static_cast<char**>(realloc(sArgs, (sArgsAllocated + kArgsGrowSize) * sizeof(char*)));
26 sArgsAllocated += kArgsGrowSize;
29 char* temp2 = strdup(inArgText);
32 sArgs[sArgsUsed++] = temp2;
33 sArgs[sArgsUsed] = nullptr;
38 // Caller has ownership of argv and is responsible for freeing the allocated
40 void SetupMacCommandLine(int& argc, char**& argv, bool forRestart) {
41 sArgs = static_cast<char**>(malloc(kArgsGrowSize * sizeof(char*)));
43 sArgsAllocated = kArgsGrowSize;
47 sBuildingCommandLine = true;
49 // Copy args, stripping anything we don't want.
50 for (int arg = 0; arg < argc; arg++) {
51 char* flag = argv[arg];
52 // Don't pass on the psn (Process Serial Number) flag from the OS, or
53 // the "-foreground" flag since it will be set below if necessary.
54 if (strncmp(flag, "-psn_", 5) != 0 && strncmp(flag, "-foreground", 11) != 0)
55 AddToCommandLine(flag);
58 // Force processing of any pending Apple GetURL Events while we're building
59 // the command line. The handlers will append to the command line rather than
60 // act directly so there is no chance we'll process them during a XUL window
61 // load and accidentally open unnecessary windows and home pages.
62 ProcessPendingGetURLAppleEvents();
64 // If the process will be relaunched, the child should be in the foreground
65 // if the parent is in the foreground. This will be communicated in a
66 // command-line argument to the child.
68 NSRunningApplication* frontApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
69 if ([frontApp isEqual:[NSRunningApplication currentApplication]]) {
70 AddToCommandLine("-foreground");
74 sBuildingCommandLine = false;
81 bool AddURLToCurrentCommandLine(const char* aURL) {
82 if (!sBuildingCommandLine) {
86 AddToCommandLine("-url");
87 AddToCommandLine(aURL);
92 } // namespace CommandLineServiceMac