Backed out 3 changesets (bug 1764201) for causing multiple failures, including build...
[gecko.git] / toolkit / xre / nsCommandLineServiceMac.mm
blobd704949b35d7841ef424ac3e8ab9ab35fe6d524d
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"
8 #include "nsString.h"
9 #include "nsTArray.h"
10 #include "MacApplicationDelegate.h"
11 #include <cstring>
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*)));
27     if (!temp) return;
28     sArgs = temp;
29     sArgsAllocated += kArgsGrowSize;
30   }
32   char* temp2 = strdup(inArgText);
33   if (!temp2) return;
35   sArgs[sArgsUsed++] = temp2;
36   sArgs[sArgsUsed] = nullptr;
38   return;
41 // Caller has ownership of argv and is responsible for freeing the allocated
42 // memory.
43 void SetupMacCommandLine(int& argc, char**& argv, bool forRestart) {
44   sArgs = static_cast<char**>(malloc(kArgsGrowSize * sizeof(char*)));
45   if (!sArgs) return;
46   sArgsAllocated = kArgsGrowSize;
47   sArgs[0] = nullptr;
48   sArgsUsed = 0;
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);
57   }
59   // Process the URLs we captured when the NSApp was first run and add them to
60   // the command line.
61   nsTArray<nsCString> startupURLs = TakeStartupURLs();
62   for (const nsCString& url : startupURLs) {
63     AddToCommandLine("-url");
64     AddToCommandLine(url.get());
65   }
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.
70   if (forRestart) {
71     NSRunningApplication* frontApp =
72         [[NSWorkspace sharedWorkspace] frontmostApplication];
73     if ([frontApp isEqual:[NSRunningApplication currentApplication]]) {
74       AddToCommandLine("-foreground");
75     }
76   }
78   free(argv);
79   argc = sArgsUsed;
80   argv = sArgs;
83 }  // namespace CommandLineServiceMac