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