File: nsAppShell.mm

package info (click to toggle)
firefox 148.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,719,656 kB
  • sloc: cpp: 7,618,171; javascript: 6,701,506; ansic: 3,781,787; python: 1,418,364; xml: 638,647; asm: 438,962; java: 186,285; sh: 62,885; makefile: 19,010; objc: 13,092; perl: 12,763; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (348 lines) | stat: -rw-r--r-- 9,955 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#import <UIKit/UIApplication.h>
#import <UIKit/UIScreen.h>
#import <UIKit/UIWindow.h>

#include "mozilla/Components.h"
#include "mozilla/dom/Document.h"
#include "nsIObserverService.h"
#include "gfxPlatform.h"
#include "nsAppRunner.h"
#include "nsAppShell.h"
#include "nsCOMPtr.h"
#include "nsComponentManager.h"
#include "nsDirectoryServiceDefs.h"
#include "nsObjCExceptions.h"
#include "nsString.h"
#include "nsIAppStartup.h"
#include "nsIRollupListener.h"
#include "nsIWidget.h"
#include "nsThreadUtils.h"
#include "nsMemoryPressure.h"
#include "nsServiceManagerUtils.h"
#include "mozilla/widget/EventDispatcher.h"
#include "mozilla/widget/ScreenManager.h"
#include "ScreenHelperUIKit.h"
#include "mozilla/Hal.h"
#include "HeadlessScreenHelper.h"
#include "nsWindow.h"
#include "nsXREDirProvider.h"

using namespace mozilla;
using namespace mozilla::widget;

nsAppShell* nsAppShell::gAppShell = NULL;

#define ALOG(args...)    \
  fprintf(stderr, args); \
  fprintf(stderr, "\n")

static void ApplicationWillTerminate(bool aCallExit);

// AppShellDelegate
//
// Acts as a delegate for the UIApplication

@interface AppShellDelegate : NSObject <UIApplicationDelegate> {
}
@property(strong, nonatomic) UIWindow* window;
@end

@implementation AppShellDelegate

- (BOOL)application:(UIApplication*)application
    didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  ALOG("[AppShellDelegate application:didFinishLaunchingWithOptions:]");

  return YES;
}

- (void)applicationWillTerminate:(UIApplication*)application {
  ALOG("[AppShellDelegate applicationWillTerminate:]");
  ApplicationWillTerminate(/* aCallExit */ false);
}

- (void)applicationDidBecomeActive:(UIApplication*)application {
  ALOG("[AppShellDelegate applicationDidBecomeActive:]");
}

- (void)applicationWillResignActive:(UIApplication*)application {
  ALOG("[AppShellDelegate applicationWillResignActive:]");
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application {
  ALOG("[AppShellDelegate applicationDidReceiveMemoryWarning:]");
  NS_NotifyOfMemoryPressure(MemoryPressureState::LowMemory);
}
@end

// nsAppShell implementation

NS_IMETHODIMP
nsAppShell::ResumeNative(void) { return nsBaseAppShell::ResumeNative(); }

nsAppShell::nsAppShell()
    : mAutoreleasePool(NULL),
      mDelegate(NULL),
      mCFRunLoop(NULL),
      mCFRunLoopSource(NULL),
      mUsingNativeEventLoop(false),
      mRunningEventLoop(false),
      mTerminated(false) {
  gAppShell = this;
}

nsAppShell::~nsAppShell() {
  if (mAutoreleasePool) {
    [mAutoreleasePool release];
    mAutoreleasePool = NULL;
  }

  if (mCFRunLoop) {
    if (mCFRunLoopSource) {
      ::CFRunLoopRemoveSource(mCFRunLoop, mCFRunLoopSource,
                              kCFRunLoopCommonModes);
      ::CFRelease(mCFRunLoopSource);
    }
    ::CFRelease(mCFRunLoop);
  }

  gAppShell = NULL;
}

// Init
//
// public
nsresult nsAppShell::Init() {
  mUsingNativeEventLoop = XRE_UseNativeEventProcessing();

  mAutoreleasePool = [[NSAutoreleasePool alloc] init];

  // Add a CFRunLoopSource to the main native run loop.  The source is
  // responsible for interrupting the run loop when Gecko events are ready.

  mCFRunLoop = [[NSRunLoop currentRunLoop] getCFRunLoop];
  NS_ENSURE_STATE(mCFRunLoop);
  ::CFRetain(mCFRunLoop);

  CFRunLoopSourceContext context;
  bzero(&context, sizeof(context));
  // context.version = 0;
  context.info = this;
  context.perform = ProcessGeckoEvents;

  mCFRunLoopSource = ::CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
  NS_ENSURE_STATE(mCFRunLoopSource);

  ::CFRunLoopAddSource(mCFRunLoop, mCFRunLoopSource, kCFRunLoopCommonModes);

  hal::Init();

  if (XRE_IsParentProcess()) {
    ScreenManager& screenManager = ScreenManager::GetSingleton();

    if (gfxPlatform::IsHeadless()) {
      screenManager.SetHelper(mozilla::MakeUnique<HeadlessScreenHelper>());
    } else {
      screenManager.SetHelper(mozilla::MakeUnique<ScreenHelperUIKit>());
    }
  }

  nsresult rv = nsBaseAppShell::Init();

  nsCOMPtr<nsIObserverService> obsServ =
      mozilla::services::GetObserverService();
  if (obsServ) {
    obsServ->AddObserver(this, "profile-after-change", false);
    obsServ->AddObserver(this, "quit-application-granted", false);
    if (XRE_IsParentProcess()) {
      obsServ->AddObserver(this, "chrome-document-loaded", false);
    }
  }

  return rv;
}

NS_IMETHODIMP nsAppShell::Observe(nsISupports* aSubject, const char* aTopic,
                                  const char16_t* aData) {
  AssertIsOnMainThread();

  bool removeObserver = false;
  if (!strcmp(aTopic, "profile-after-change")) {
    // Gecko on iOS follows the iOS app model where it never stops until it is
    // killed by the system or told explicitly to quit. Therefore, we should
    // *not* exit Gecko when there is no window or the last window is closed.
    // nsIAppStartup::Quit will still force Gecko to exit.
    nsCOMPtr<nsIAppStartup> appStartup = components::AppStartup::Service();
    if (appStartup) {
      appStartup->EnterLastWindowClosingSurvivalArea();
    }
    removeObserver = true;
  } else if (!strcmp(aTopic, "quit-application-granted")) {
    // We are told explicitly to quit, perhaps due to
    // nsIAppStartup::Quit being called. We should release our hold on
    // nsIAppStartup and let it continue to quit.
    nsCOMPtr<nsIAppStartup> appStartup = components::AppStartup::Service();
    if (appStartup) {
      appStartup->ExitLastWindowClosingSurvivalArea();
    }
    removeObserver = true;
  } else if (!strcmp(aTopic, "chrome-document-loaded")) {
    // Set the global ready state and enable the window event dispatcher
    // for this particular GeckoView.
    nsCOMPtr<dom::Document> doc = do_QueryInterface(aSubject);
    MOZ_ASSERT(doc);
    if (const RefPtr<nsWindow> window = nsWindow::From(doc->GetWindow())) {
      RefPtr<EventDispatcher> dispatcher = window->GetEventDispatcher();
      dispatcher->Activate();
    }
  } else {
    return nsBaseAppShell::Observe(aSubject, aTopic, aData);
  }

  if (removeObserver) {
    nsCOMPtr<nsIObserverService> obsServ =
        mozilla::services::GetObserverService();
    if (obsServ) {
      obsServ->RemoveObserver(this, aTopic);
    }
  }
  return NS_OK;
}

// ProcessGeckoEvents
//
// The "perform" target of mCFRunLoop, called when mCFRunLoopSource is
// signalled from ScheduleNativeEventCallback.
//
// protected static
void nsAppShell::ProcessGeckoEvents(void* aInfo) {
  nsAppShell* self = static_cast<nsAppShell*>(aInfo);
  if (self->mRunningEventLoop) {
    self->mRunningEventLoop = false;
  }
  self->NativeEventCallback();
  self->Release();
}

// ScheduleNativeEventCallback
//
// protected virtual
void nsAppShell::ScheduleNativeEventCallback() {
  NS_ADDREF_THIS();

  // This will invoke ProcessGeckoEvents on the main thread.
  ::CFRunLoopSourceSignal(mCFRunLoopSource);
  ::CFRunLoopWakeUp(mCFRunLoop);
}

// ProcessNextNativeEvent
//
// protected virtual
bool nsAppShell::ProcessNextNativeEvent(bool aMayWait) {
  NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;

  if (mTerminated) return false;

  bool wasRunningEventLoop = mRunningEventLoop;
  mRunningEventLoop = aMayWait;
  NSString* currentMode = nil;
  NSDate* waitUntil = nil;
  if (aMayWait) waitUntil = [NSDate distantFuture];
  NSRunLoop* currentRunLoop = [NSRunLoop currentRunLoop];

  do {
    currentMode = [currentRunLoop currentMode];
    if (!currentMode) currentMode = NSDefaultRunLoopMode;

    if (aMayWait) {
      [currentRunLoop runMode:currentMode beforeDate:waitUntil];
    } else {
      [currentRunLoop acceptInputForMode:currentMode beforeDate:waitUntil];
    }
  } while (mRunningEventLoop);

  mRunningEventLoop = wasRunningEventLoop;

  NS_OBJC_END_TRY_IGNORE_BLOCK;

  return false;
}

// Run
//
// public
NS_IMETHODIMP
nsAppShell::Run(void) {
  ALOG("nsAppShell::Run");

  nsresult rv = NS_OK;
  if (mUsingNativeEventLoop) {
    char argv[1][4] = {"app"};
    UIApplicationMain(1, (char**)argv, nil, @"AppShellDelegate");
    // UIApplicationMain doesn't exit. :-(
  } else {
    rv = nsBaseAppShell::Run();
  }

  return rv;
}

NS_IMETHODIMP
nsAppShell::Exit(void) {
  if (mTerminated) return NS_OK;

  mTerminated = true;

  if (mUsingNativeEventLoop) {
    // Dispatch a native event to the main queue to terminate. XPCOM doesn't
    // like being shut down from within an XPCOM runnable, so we cannot use
    // `NS_DispatchToMainThread` here.
    dispatch_async(dispatch_get_main_queue(), ^{
      ApplicationWillTerminate(true);
    });
    return NS_OK;
  }

  return nsBaseAppShell::Exit();
}

static bool gNotifiedWillTerminate = false;

static void ApplicationWillTerminate(bool aCallExit) {
  if (std::exchange(gNotifiedWillTerminate, true)) {
    return;
  }

  // Perform the steps which would normally happen after nsAppShell::Run, such
  // as `~ScopedXPCOMStartup`, as UIApplicationMain will never shutdown.
  if (nsCOMPtr<nsIAppStartup> appStartup = components::AppStartup::Service()) {
    // Ensure quit notifications have fired to start the shutdown process, and
    // notify listeners.
    bool userAllowedQuit;
    appStartup->Quit(nsIAppStartup::eForceQuit, 0, &userAllowedQuit);

    appStartup->DestroyHiddenWindow();
  }

  gDirServiceProvider->DoShutdown();

  WriteConsoleLog();

  // Release the final reference to the `nsIServiceManager` which is being held
  // by `ScopedXPCOMStartup`, as we will never destroy that object.
  nsIServiceManager* servMgr = nsComponentManagerImpl::gComponentManager;
  NS_ShutdownXPCOM(servMgr);

  // Matches the ScopedLogger initialized in `XRE_main` which will never be
  // cleaned up.
  NS_LogTerm();

  if (aCallExit) {
    _exit(0);
  }
}