File: window_applescript.mm

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (326 lines) | stat: -rw-r--r-- 10,032 bytes parent folder | download | duplicates (6)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/ui/cocoa/applescript/window_applescript.h"

#include <memory>

#import "base/apple/foundation_util.h"
#include "base/memory/weak_ptr.h"
#include "base/notreached.h"
#include "base/strings/sys_string_conversions.h"
#include "base/time/time.h"
#import "chrome/browser/app_controller_mac.h"
#import "chrome/browser/chrome_browser_application_mac.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/cocoa/applescript/constants_applescript.h"
#include "chrome/browser/ui/cocoa/applescript/error_applescript.h"
#import "chrome/browser/ui/cocoa/applescript/tab_applescript.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_context.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_enums.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_user_gesture_details.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/web_contents.h"

@interface WindowAppleScript ()

// The NSWindow that corresponds to this window.
@property(readonly) NSWindow* nativeHandle;

@end

@implementation WindowAppleScript {
  // A note about lifetimes: It's not expected that this object will ever be
  // deleted behind the back of this class. AppleScript does not hold onto
  // objects between script runs; it will retain the object specifier, and if
  // needed again, AppleScript will re-iterate over the objects, and look for
  // the specified object. However, there's no hard guarantee that a race
  // couldn't be made to happen, and in tests things are torn down at odd times,
  // so it's best to use a real weak pointer.
  base::WeakPtr<Browser> _browser;
}

- (instancetype)init {
  // Check which mode to open a new window.
  NSScriptCommand* command = [NSScriptCommand currentCommand];
  NSString* mode = command.evaluatedArguments[@"KeyDictionary"][@"mode"];

  Profile* lastProfile = AppController.sharedController.lastProfile;
  if (!lastProfile) {
    AppleScript::SetError(AppleScript::Error::kGetProfile);
    return nil;
  } else {
    // Ensure that the profile is a non-OTR profile, so that it's possible to
    // create a non-OTR window, below.
    lastProfile = lastProfile->GetOriginalProfile();
  }

  Profile* profile;
  if ([mode isEqualToString:AppleScript::kIncognitoWindowMode]) {
    profile = lastProfile->GetPrimaryOTRProfile(/*create_if_needed=*/true);
  } else if ([mode isEqualToString:AppleScript::kNormalWindowMode] || !mode) {
    profile = lastProfile;
  } else {
    // Mode cannot be anything else.
    AppleScript::SetError(AppleScript::Error::kInvalidMode);
    return nil;
  }
  // Set the mode to nil, to ensure that it is not set once more.
  [command.evaluatedArguments[@"KeyDictionary"] setValue:nil forKey:@"mode"];
  return [self initWithProfile:profile];
}

- (instancetype)initWithProfile:(Profile*)aProfile {
  if (!aProfile) {
    self = nil;
    return nil;
  }

  if ((self = [super init])) {
    // Since AppleScript requests can arrive at any time, including during
    // browser shutdown or profile deletion, we have to check whether it's okay
    // to spawn a new browser for the specified profile or not.
    if (Browser::GetCreationStatusForProfile(aProfile) !=
        Browser::CreationStatus::kOk) {
      self = nil;
      return nil;
    }

    Browser* browser = Browser::Create(
        Browser::CreateParams(aProfile, /*user_gesture=*/false));
    chrome::NewTab(browser);
    browser->window()->Show();

    _browser = browser->AsWeakPtr();
    self.uniqueID =
        [NSString stringWithFormat:@"%d", _browser->session_id().id()];
  }
  return self;
}

- (instancetype)initWithBrowser:(Browser*)browser {
  if (!browser) {
    self = nil;
    return nil;
  }

  if ((self = [super init])) {
    // It is safe to be weak, if a window goes away (eg user closing a window)
    // the AppleScript runtime calls appleScriptWindows in
    // BrowserCrApplication and this particular window is never returned.
    _browser = browser->AsWeakPtr();
    self.uniqueID =
        [NSString stringWithFormat:@"%d", _browser->session_id().id()];
  }
  return self;
}

- (NSWindow*)nativeHandle {
  if (!_browser) {
    return nil;
  }

  // window() can be null during startup.
  if (_browser->window()) {
    return _browser->window()->GetNativeWindow().GetNativeNSWindow();
  }
  return nil;
}

- (NSNumber*)activeTabIndex {
  if (!_browser) {
    return nil;
  }

  // Note: AppleScript is 1-based, that is lists begin with index 1.
  int activeTabIndex = _browser->tab_strip_model()->active_index() + 1;
  if (!activeTabIndex) {
    return nil;
  }
  return @(activeTabIndex);
}

- (void)setActiveTabIndex:(NSNumber*)anActiveTabIndex {
  if (!_browser) {
    return;
  }

  // Note: AppleScript is 1-based, that is lists begin with index 1.
  int atIndex = anActiveTabIndex.intValue - 1;
  if (atIndex >= 0 && atIndex < _browser->tab_strip_model()->count()) {
    _browser->tab_strip_model()->ActivateTabAt(
        atIndex, TabStripUserGestureDetails(
                     TabStripUserGestureDetails::GestureType::kOther));
  } else {
    AppleScript::SetError(AppleScript::Error::kInvalidTabIndex);
  }
}

- (NSString*)givenName {
  if (!_browser) {
    return nil;
  }

  return base::SysUTF8ToNSString(_browser->user_title());
}

- (void)setGivenName:(NSString*)name {
  if (!_browser) {
    return;
  }

  _browser->SetWindowUserTitle(base::SysNSStringToUTF8(name));
}

- (NSString*)mode {
  if (!_browser) {
    return nil;
  }

  Profile* profile = _browser->profile();
  if (profile->IsOffTheRecord()) {
    return AppleScript::kIncognitoWindowMode;
  }
  return AppleScript::kNormalWindowMode;
}

- (void)setMode:(NSString*)theMode {
  // Cannot set mode after window is created.
  if (theMode) {
    AppleScript::SetError(AppleScript::Error::kSetMode);
  }
}

- (TabAppleScript*)activeTab {
  if (!_browser) {
    return nil;
  }

  TabAppleScript* currentTab = [[TabAppleScript alloc]
      initWithWebContents:_browser->tab_strip_model()->GetActiveWebContents()];
  [currentTab setContainer:self property:AppleScript::kTabsProperty];
  return currentTab;
}

- (NSArray<TabAppleScript*>*)tabs {
  if (!_browser) {
    return nil;
  }

  TabStripModel* tabStrip = _browser->tab_strip_model();
  NSMutableArray* tabs = [NSMutableArray arrayWithCapacity:tabStrip->count()];

  for (int i = 0; i < tabStrip->count(); ++i) {
    // Check to see if tab is closing.
    content::WebContents* webContents = tabStrip->GetWebContentsAt(i);
    if (webContents->IsBeingDestroyed()) {
      continue;
    }

    TabAppleScript* tab =
        [[TabAppleScript alloc] initWithWebContents:webContents];
    [tab setContainer:self property:AppleScript::kTabsProperty];
    [tabs addObject:tab];
  }
  return tabs;
}

- (void)insertInTabs:(TabAppleScript*)aTab {
  if (!_browser) {
    return;
  }

  // This method gets called when a new tab is created so
  // the container and property are set here.
  [aTab setContainer:self property:AppleScript::kTabsProperty];

  // Set how long it takes a tab to be created.
  base::TimeTicks newTabStartTime = base::TimeTicks::Now();
  content::WebContents* contents = chrome::AddSelectedTabWithURL(
      _browser.get(), GURL(chrome::kChromeUINewTabURL),
      ui::PAGE_TRANSITION_TYPED);
  CoreTabHelper* core_tab_helper = CoreTabHelper::FromWebContents(contents);
  core_tab_helper->set_new_tab_start_time(newTabStartTime);
  [aTab setWebContents:contents];
}

- (void)insertInTabs:(TabAppleScript*)aTab atIndex:(int)index {
  if (!_browser) {
    return;
  }

  // This method gets called when a new tab is created so
  // the container and property are set here.
  [aTab setContainer:self property:AppleScript::kTabsProperty];

  // Set how long it takes a tab to be created.
  base::TimeTicks newTabStartTime = base::TimeTicks::Now();
  NavigateParams params(_browser.get(), GURL(chrome::kChromeUINewTabURL),
                        ui::PAGE_TRANSITION_TYPED);
  params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
  params.tabstrip_index = index;
  Navigate(&params);
  CoreTabHelper* core_tab_helper =
      CoreTabHelper::FromWebContents(params.navigated_or_inserted_contents);
  core_tab_helper->set_new_tab_start_time(newTabStartTime);

  [aTab setWebContents:params.navigated_or_inserted_contents];
}

- (void)removeFromTabsAtIndex:(int)index {
  if (!_browser) {
    return;
  }

  if (index < 0 || index >= _browser->tab_strip_model()->count()) {
    return;
  }
  _browser->tab_strip_model()->CloseWebContentsAt(
      index, TabCloseTypes::CLOSE_CREATE_HISTORICAL_TAB);
}

- (NSNumber*)orderedIndex {
  return @(self.nativeHandle.orderedIndex);
}

- (void)setOrderedIndex:(NSNumber*)anIndex {
  int index = anIndex.intValue - 1;
  if (index < 0 || index >= static_cast<int>(chrome::GetTotalBrowserCount())) {
    AppleScript::SetError(AppleScript::Error::kWrongIndex);
    return;
  }
  self.nativeHandle.orderedIndex = index;
}

// Get and set values from the associated NSWindow.
- (id)valueForUndefinedKey:(NSString*)key {
  return [self.nativeHandle valueForKey:key];
}

- (void)setValue:(id)value forUndefinedKey:(NSString*)key {
  [self.nativeHandle setValue:value forKey:key];
}

- (void)handlesCloseScriptCommand:(NSCloseCommand*)command {
  if (!_browser) {
    return;
  }

  // window() can be null during startup.
  if (_browser->window()) {
    _browser->window()->Close();
  }
}

@end