1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "chrome/test/base/interactive_test_utils.h" 6 7 #include <Carbon/Carbon.h> 8 #import <Cocoa/Cocoa.h> 9 10 #include "base/bind.h" 11 #include "base/logging.h" 12 #include "base/message_loop/message_loop.h" 13 #include "chrome/browser/ui/browser.h" 14 #include "chrome/browser/ui/browser_window.h" 15 #import "chrome/browser/ui/cocoa/view_id_util.h" 16 #include "ui/base/test/ui_controls.h" 17 18 namespace ui_test_utils { 19 20 bool IsViewFocused(const Browser* browser, ViewID vid) { 21 NSWindow* window = browser->window()->GetNativeWindow(); 22 DCHECK(window); 23 NSView* view = view_id_util::GetView(window, vid); 24 if (!view) 25 return false; 26 27 NSResponder* firstResponder = [window firstResponder]; 28 if (firstResponder == static_cast<NSResponder*>(view)) 29 return true; 30 31 // Handle the special case of focusing a TextField. 32 if ([firstResponder isKindOfClass:[NSTextView class]]) { 33 NSView* delegate = static_cast<NSView*>([(NSTextView*)firstResponder 34 delegate]); 35 if (delegate == view) 36 return true; 37 } 38 39 return false; 40 } 41 42 void ClickOnView(const Browser* browser, ViewID vid) { 43 NSWindow* window = browser->window()->GetNativeWindow(); 44 DCHECK(window); 45 NSView* view = view_id_util::GetView(window, vid); 46 DCHECK(view); 47 MoveMouseToCenterAndPress( 48 view, 49 ui_controls::LEFT, 50 ui_controls::DOWN | ui_controls::UP, 51 base::MessageLoop::QuitClosure()); 52 content::RunMessageLoop(); 53 } 54 55 void HideNativeWindow(gfx::NativeWindow window) { 56 [window orderOut:nil]; 57 } 58 59 bool ShowAndFocusNativeWindow(gfx::NativeWindow window) { 60 // Make sure an unbundled program can get the input focus. 61 ProcessSerialNumber psn = { 0, kCurrentProcess }; 62 TransformProcessType(&psn,kProcessTransformToForegroundApplication); 63 SetFrontProcess(&psn); 64 65 [window makeKeyAndOrderFront:nil]; 66 return true; 67 } 68 69 void MoveMouseToCenterAndPress( 70 NSView* view, 71 ui_controls::MouseButton button, 72 int state, 73 const base::Closure& task) { 74 DCHECK(view); 75 NSWindow* window = [view window]; 76 DCHECK(window); 77 NSScreen* screen = [window screen]; 78 DCHECK(screen); 79 80 // Converts the center position of the view into the coordinates accepted 81 // by SendMouseMoveNotifyWhenDone() method. 82 NSRect bounds = [view bounds]; 83 NSPoint center = NSMakePoint(NSMidX(bounds), NSMidY(bounds)); 84 center = [view convertPoint:center toView:nil]; 85 center = [window convertBaseToScreen:center]; 86 center = NSMakePoint(center.x, [screen frame].size.height - center.y); 87 88 ui_controls::SendMouseMoveNotifyWhenDone( 89 center.x, center.y, 90 base::Bind(&internal::ClickTask, button, state, task)); 91 } 92 93 } // namespace ui_test_utils 94