llopenglview-objc.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /**
  2. * @file llopenglview-objc.mm
  3. * @brief Class implementation for most of the Mac facing window functionality.
  4. *
  5. * $LicenseInfo:firstyear=2000&license=viewerlgpl$
  6. * Second Life Viewer Source Code
  7. * Copyright (C) 2010, Linden Research, Inc.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation;
  12. * version 2.1 of the License only.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with this library; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  24. * $/LicenseInfo$
  25. */
  26. #import "llopenglview-objc.h"
  27. #import "llwindowmacosx-objc.h"
  28. #import "llappdelegate-objc.h"
  29. #pragma mark local functions
  30. // Fix for deprecated convertScreenToBase, should make new function instead.
  31. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  32. extern bool gHiDPISupport;
  33. NativeKeyEventData extractKeyDataFromKeyEvent(NSEvent* theEvent)
  34. {
  35. NativeKeyEventData eventData;
  36. eventData.mKeyEvent = NativeKeyEventData::KEYUNKNOWN;
  37. eventData.mEventType = [theEvent type];
  38. eventData.mEventModifiers = [theEvent modifierFlags];
  39. eventData.mEventKeyCode = [theEvent keyCode];
  40. NSString *strEventChars = [theEvent characters];
  41. eventData.mEventChars = (strEventChars.length) ? [strEventChars characterAtIndex:0] : 0;
  42. NSString *strEventUChars = [theEvent charactersIgnoringModifiers];
  43. eventData.mEventUnmodChars = (strEventUChars.length) ? [strEventUChars characterAtIndex:0] : 0;
  44. eventData.mEventRepeat = [theEvent isARepeat];
  45. return eventData;
  46. }
  47. NativeKeyEventData extractKeyDataFromModifierEvent(NSEvent* theEvent)
  48. {
  49. NativeKeyEventData eventData;
  50. eventData.mKeyEvent = NativeKeyEventData::KEYUNKNOWN;
  51. eventData.mEventType = [theEvent type];
  52. eventData.mEventModifiers = [theEvent modifierFlags];
  53. eventData.mEventKeyCode = [theEvent keyCode];
  54. return eventData;
  55. }
  56. attributedStringInfo getSegments(NSAttributedString *str)
  57. {
  58. attributedStringInfo segments;
  59. segment_lengths seg_lengths;
  60. segment_standouts seg_standouts;
  61. NSRange effectiveRange;
  62. NSRange limitRange = NSMakeRange(0, [str length]);
  63. while (limitRange.length > 0) {
  64. NSNumber *attr = [str attribute:NSUnderlineStyleAttributeName atIndex:limitRange.location longestEffectiveRange:&effectiveRange inRange:limitRange];
  65. limitRange = NSMakeRange(NSMaxRange(effectiveRange), NSMaxRange(limitRange) - NSMaxRange(effectiveRange));
  66. if (effectiveRange.length <= 0)
  67. {
  68. effectiveRange.length = 1;
  69. }
  70. if ([attr integerValue] == 2)
  71. {
  72. seg_lengths.push_back(effectiveRange.length);
  73. seg_standouts.push_back(true);
  74. }
  75. else
  76. {
  77. seg_lengths.push_back(effectiveRange.length);
  78. seg_standouts.push_back(false);
  79. }
  80. }
  81. segments.seg_lengths = seg_lengths;
  82. segments.seg_standouts = seg_standouts;
  83. return segments;
  84. }
  85. #pragma mark class implementations
  86. @implementation NSScreen (PointConversion)
  87. + (NSScreen *)currentScreenForMouseLocation
  88. {
  89. NSPoint mouseLocation = [NSEvent mouseLocation];
  90. NSEnumerator *screenEnumerator = [[NSScreen screens] objectEnumerator];
  91. NSScreen *screen;
  92. while ((screen = [screenEnumerator nextObject]) && !NSMouseInRect(mouseLocation, screen.frame, NO))
  93. ;
  94. return screen;
  95. }
  96. - (NSPoint)convertPointToScreenCoordinates:(NSPoint)aPoint
  97. {
  98. float normalizedX = fabs(fabs(self.frame.origin.x) - fabs(aPoint.x));
  99. float normalizedY = aPoint.y - self.frame.origin.y;
  100. return NSMakePoint(normalizedX, normalizedY);
  101. }
  102. - (NSPoint)flipPoint:(NSPoint)aPoint
  103. {
  104. return NSMakePoint(aPoint.x, self.frame.size.height - aPoint.y);
  105. }
  106. @end
  107. @implementation LLOpenGLView
  108. - (unsigned long)getVramSize
  109. {
  110. CGLRendererInfoObj info = 0;
  111. GLint vram_megabytes = 0;
  112. int num_renderers = 0;
  113. CGLError the_err = CGLQueryRendererInfo (CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay), &info, &num_renderers);
  114. if(0 == the_err)
  115. {
  116. CGLDescribeRenderer (info, 0, kCGLRPTextureMemoryMegabytes, &vram_megabytes);
  117. CGLDestroyRendererInfo (info);
  118. }
  119. else
  120. {
  121. vram_megabytes = 256;
  122. }
  123. return (unsigned long)vram_megabytes; // return value is in megabytes.
  124. }
  125. - (void)viewDidMoveToWindow
  126. {
  127. [[NSNotificationCenter defaultCenter] addObserver:self
  128. selector:@selector(windowResized:) name:NSWindowDidResizeNotification
  129. object:[self window]];
  130. [[NSNotificationCenter defaultCenter] addObserver:self
  131. selector:@selector(windowWillMiniaturize:) name:NSWindowWillMiniaturizeNotification
  132. object:[self window]];
  133. [[NSNotificationCenter defaultCenter] addObserver:self
  134. selector:@selector(windowDidDeminiaturize:) name:NSWindowDidDeminiaturizeNotification
  135. object:[self window]];
  136. [[NSNotificationCenter defaultCenter] addObserver:self
  137. selector:@selector(windowDidBecomeKey:) name:NSWindowDidBecomeKeyNotification
  138. object:[self window]];
  139. [[NSNotificationCenter defaultCenter] addObserver:self
  140. selector:@selector(windowDidChangeScreen:) name:NSWindowDidChangeScreenNotification
  141. object:[self window]];
  142. NSRect wnd_rect = [[self window] frame];
  143. NSRect dev_rect = [self convertRectToBacking:wnd_rect];
  144. if (!NSEqualSizes(wnd_rect.size, dev_rect.size))
  145. {
  146. callResize(dev_rect.size.width, dev_rect.size.height);
  147. }
  148. }
  149. - (void)windowResized:(NSNotification *)notification;
  150. {
  151. NSSize dev_sz = gHiDPISupport ? [self convertSizeToBacking:[self frame].size] : [self frame].size;
  152. callResize(dev_sz.width, dev_sz.height);
  153. }
  154. - (void)windowWillMiniaturize:(NSNotification *)notification;
  155. {
  156. callWindowHide();
  157. }
  158. - (void)windowDidDeminiaturize:(NSNotification *)notification;
  159. {
  160. callWindowUnhide();
  161. }
  162. - (void)windowDidBecomeKey:(NSNotification *)notification;
  163. {
  164. mModifiers = [NSEvent modifierFlags];
  165. }
  166. -(void)windowDidChangeScreen:(NSNotification *)notification;
  167. {
  168. callWindowDidChangeScreen();
  169. }
  170. - (void)dealloc
  171. {
  172. [[NSNotificationCenter defaultCenter] removeObserver:self];
  173. [super dealloc];
  174. }
  175. - (id) init
  176. {
  177. return [self initWithFrame:[self bounds] withSamples:2 andVsync:TRUE andCoreGL:FALSE];
  178. }
  179. - (id) initWithFrame:(NSRect)frame withSamples:(NSUInteger)samples andVsync:(BOOL)vsync andCoreGL:(BOOL)core_gl
  180. {
  181. [self registerForDraggedTypes:[NSArray arrayWithObject:NSURLPboardType]];
  182. [self initWithFrame:frame];
  183. // Initialize with a default "safe" pixel format that will work with versions dating back to OS X 10.6.
  184. // Any specialized pixel formats, i.e. a core profile pixel format, should be initialized through rebuildContextWithFormat.
  185. // 10.7 and 10.8 don't really care if we're defining a profile or not. If we don't explicitly request a core or legacy profile, it'll always assume a legacy profile (for compatibility reasons).
  186. NSOpenGLPixelFormatAttribute attrs[] = {
  187. NSOpenGLPFANoRecovery,
  188. NSOpenGLPFADoubleBuffer,
  189. NSOpenGLPFAClosestPolicy,
  190. NSOpenGLPFAAccelerated,
  191. NSOpenGLPFASampleBuffers,
  192. static_cast<NSOpenGLPixelFormatAttribute>(samples > 0 ? 1 : 0),
  193. NSOpenGLPFASamples, static_cast<NSOpenGLPixelFormatAttribute>(samples),
  194. NSOpenGLPFAStencilSize, 8,
  195. NSOpenGLPFADepthSize, 24,
  196. NSOpenGLPFAAlphaSize, 8,
  197. NSOpenGLPFAColorSize, 24,
  198. NSOpenGLPFAOpenGLProfile,
  199. (core_gl ? NSOpenGLProfileVersion3_2Core
  200. : NSOpenGLProfileVersionLegacy),
  201. 0
  202. };
  203. NSOpenGLPixelFormat *pixelFormat = [[[NSOpenGLPixelFormat alloc] initWithAttributes:attrs] autorelease];
  204. if (pixelFormat == nil)
  205. {
  206. NSLog(@"Failed to create pixel format !", nil);
  207. return nil;
  208. }
  209. NSOpenGLContext *glContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
  210. if (glContext == nil)
  211. {
  212. NSLog(@"Failed to create OpenGL context !", nil);
  213. return nil;
  214. }
  215. [self setPixelFormat:pixelFormat];
  216. // For Retina support
  217. // IMPORTANT NOTE: this code seems totally insufficent, when the viewer is
  218. // compiled with Xcode 10 or 11: HiDPI support must be specified via a true
  219. // or false value for a NSHighResolutionCapable key in the Info.plist file,
  220. // or bad things happen... This is the reason why this code is actually
  221. // hard-wired to non-HiDPI mode (gHiDPISupport always false) in the Cool VL
  222. // Viewer. HB
  223. if (gHiDPISupport)
  224. {
  225. [self setWantsBestResolutionOpenGLSurface:YES];
  226. }
  227. else
  228. {
  229. [self setWantsBestResolutionOpenGLSurface:NO];
  230. }
  231. [self setOpenGLContext:glContext];
  232. [glContext setView:self];
  233. [glContext makeCurrentContext];
  234. if (vsync)
  235. {
  236. GLint value = 1;
  237. [glContext setValues:&value forParameter:NSOpenGLCPSwapInterval];
  238. }
  239. else
  240. {
  241. // Suppress this error after move to Xcode 7:
  242. // error: null passed to a callee that requires a non-null argument [-Werror,-Wnonnull]
  243. // Tried using ObjC 'nonnull' keyword as per SO article but didn't build
  244. GLint swapInterval=0;
  245. [glContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
  246. }
  247. return self;
  248. }
  249. - (BOOL) rebuildContext
  250. {
  251. return [self rebuildContextWithFormat:[self pixelFormat]];
  252. }
  253. - (BOOL) rebuildContextWithFormat:(NSOpenGLPixelFormat *)format
  254. {
  255. NSOpenGLContext *ctx = [self openGLContext];
  256. [ctx clearDrawable];
  257. [ctx initWithFormat:format shareContext:nil];
  258. if (ctx == nil)
  259. {
  260. NSLog(@"Failed to create OpenGL context !", nil);
  261. return false;
  262. }
  263. [self setOpenGLContext:ctx];
  264. [ctx setView:self];
  265. [ctx makeCurrentContext];
  266. return true;
  267. }
  268. - (CGLContextObj)getCGLContextObj
  269. {
  270. NSOpenGLContext *ctx = [self openGLContext];
  271. return (CGLContextObj)[ctx CGLContextObj];
  272. }
  273. - (CGLPixelFormatObj*)getCGLPixelFormatObj
  274. {
  275. NSOpenGLPixelFormat *fmt = [self pixelFormat];
  276. return (CGLPixelFormatObj*)[fmt CGLPixelFormatObj];
  277. }
  278. // Various events can be intercepted by our view, thus not reaching our window.
  279. // Intercept these events, and pass them to the window as needed. - Geenz
  280. - (void) mouseDown:(NSEvent *)theEvent
  281. {
  282. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  283. mMousePos[0] = mPoint.x;
  284. mMousePos[1] = mPoint.y;
  285. // Apparently people still use this?
  286. if ([theEvent modifierFlags] & NSCommandKeyMask &&
  287. !([theEvent modifierFlags] & NSControlKeyMask) &&
  288. !([theEvent modifierFlags] & NSShiftKeyMask) &&
  289. !([theEvent modifierFlags] & NSAlternateKeyMask) &&
  290. !([theEvent modifierFlags] & NSAlphaShiftKeyMask) &&
  291. !([theEvent modifierFlags] & NSFunctionKeyMask) &&
  292. !([theEvent modifierFlags] & NSHelpKeyMask))
  293. {
  294. callRightMouseDown(mMousePos, [theEvent modifierFlags]);
  295. mSimulatedRightClick = true;
  296. }
  297. else
  298. {
  299. if ([theEvent clickCount] >= 2)
  300. {
  301. callDoubleClick(mMousePos, [theEvent modifierFlags]);
  302. }
  303. else if ([theEvent clickCount] == 1)
  304. {
  305. callLeftMouseDown(mMousePos, [theEvent modifierFlags]);
  306. }
  307. }
  308. }
  309. - (void) mouseUp:(NSEvent *)theEvent
  310. {
  311. if (mSimulatedRightClick)
  312. {
  313. callRightMouseUp(mMousePos, [theEvent modifierFlags]);
  314. mSimulatedRightClick = false;
  315. }
  316. else
  317. {
  318. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  319. mMousePos[0] = mPoint.x;
  320. mMousePos[1] = mPoint.y;
  321. callLeftMouseUp(mMousePos, [theEvent modifierFlags]);
  322. }
  323. }
  324. - (void) rightMouseDown:(NSEvent *)theEvent
  325. {
  326. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  327. mMousePos[0] = mPoint.x;
  328. mMousePos[1] = mPoint.y;
  329. callRightMouseDown(mMousePos, [theEvent modifierFlags]);
  330. }
  331. - (void) rightMouseUp:(NSEvent *)theEvent
  332. {
  333. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  334. mMousePos[0] = mPoint.x;
  335. mMousePos[1] = mPoint.y;
  336. callRightMouseUp(mMousePos, [theEvent modifierFlags]);
  337. }
  338. - (void)mouseMoved:(NSEvent *)theEvent
  339. {
  340. NSPoint dev_delta = gHiDPISupport ? [self convertPointToBacking:NSMakePoint([theEvent deltaX], [theEvent deltaY])] : NSMakePoint([theEvent deltaX], [theEvent deltaY]);
  341. float mouseDeltas[] = {
  342. float(dev_delta.x),
  343. float(dev_delta.y)
  344. };
  345. callDeltaUpdate(mouseDeltas, 0);
  346. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  347. mMousePos[0] = mPoint.x;
  348. mMousePos[1] = mPoint.y;
  349. callMouseMoved(mMousePos, 0);
  350. }
  351. // NSWindow doesn't trigger mouseMoved when the mouse is being clicked and dragged.
  352. // Use mouseDragged for situations like this to trigger our movement callback instead.
  353. - (void) mouseDragged:(NSEvent *)theEvent
  354. {
  355. // Trust the deltas supplied by NSEvent.
  356. // The old CoreGraphics APIs we previously relied on are now flagged as obsolete.
  357. // NSEvent isn't obsolete, and provides us with the correct deltas.
  358. NSPoint dev_delta = gHiDPISupport ? [self convertPointToBacking:NSMakePoint([theEvent deltaX], [theEvent deltaY])] : NSMakePoint([theEvent deltaX], [theEvent deltaY]);
  359. float mouseDeltas[] = {
  360. float(dev_delta.x),
  361. float(dev_delta.y)
  362. };
  363. callDeltaUpdate(mouseDeltas, 0);
  364. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  365. mMousePos[0] = mPoint.x;
  366. mMousePos[1] = mPoint.y;
  367. callMouseDragged(mMousePos, 0);
  368. }
  369. - (void) otherMouseDown:(NSEvent *)theEvent
  370. {
  371. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  372. mMousePos[0] = mPoint.x;
  373. mMousePos[1] = mPoint.y;
  374. callMiddleMouseDown(mMousePos, [theEvent modifierFlags]);
  375. }
  376. - (void) otherMouseUp:(NSEvent *)theEvent
  377. {
  378. NSPoint mPoint = gHiDPISupport ? [self convertPointToBacking:[theEvent locationInWindow]] : [theEvent locationInWindow];
  379. mMousePos[0] = mPoint.x;
  380. mMousePos[1] = mPoint.y;
  381. callMiddleMouseUp(mMousePos, [theEvent modifierFlags]);
  382. }
  383. - (void) rightMouseDragged:(NSEvent *)theEvent
  384. {
  385. [self mouseDragged:theEvent];
  386. }
  387. - (void) otherMouseDragged:(NSEvent *)theEvent
  388. {
  389. [self mouseDragged:theEvent];
  390. }
  391. - (void) scrollWheel:(NSEvent *)theEvent
  392. {
  393. callScrollMoved(-[theEvent deltaY]);
  394. }
  395. - (void) mouseExited:(NSEvent *)theEvent
  396. {
  397. callMouseExit();
  398. }
  399. - (void) keyUp:(NSEvent *)theEvent
  400. {
  401. NativeKeyEventData eventData = extractKeyDataFromKeyEvent(theEvent);
  402. eventData.mKeyEvent = NativeKeyEventData::KEYUP;
  403. callKeyUp(&eventData, [theEvent keyCode], [theEvent modifierFlags]);
  404. }
  405. - (void) keyDown:(NSEvent *)theEvent
  406. {
  407. NativeKeyEventData eventData = extractKeyDataFromKeyEvent(theEvent);
  408. eventData.mKeyEvent = NativeKeyEventData::KEYDOWN;
  409. uint keycode = [theEvent keyCode];
  410. // We must not depend on flagsChange event to detect modifier flags changed,
  411. // must depend on the modifire flags in the event parameter.
  412. // Because flagsChange event handler misses event when other window is activated,
  413. // e.g. OS Window for upload something or Input Window...
  414. // mModifiers instance variable is for insertText: or insertText:replacementRange: (by Pell Smit)
  415. mModifiers = [theEvent modifierFlags];
  416. bool acceptsText = mHasMarkedText ? false : callKeyDown(&eventData, keycode, mModifiers);
  417. unichar ch;
  418. if (acceptsText &&
  419. !mMarkedTextAllowed &&
  420. !(mModifiers & (NSControlKeyMask | NSCommandKeyMask)) && // commands don't invoke InputWindow
  421. ![(LLAppDelegate*)[NSApp delegate] romanScript] &&
  422. (ch = [[theEvent charactersIgnoringModifiers] characterAtIndex:0]) > ' ' &&
  423. ch != NSDeleteCharacter &&
  424. (ch < 0xF700 || ch > 0xF8FF)) // 0xF700-0xF8FF: reserved for function keys on the keyboard(from NSEvent.h)
  425. {
  426. [(LLAppDelegate*)[NSApp delegate] showInputWindow:true withEvent:theEvent];
  427. }
  428. else
  429. {
  430. [[self inputContext] handleEvent:theEvent];
  431. }
  432. // OS X (intentionally) does not send key-up information on cmd-key
  433. // combinations. Since SL assumes we receive those, we fake it here.
  434. if (mModifiers & NSCommandKeyMask && !mHasMarkedText)
  435. {
  436. eventData.mKeyEvent = NativeKeyEventData::KEYUP;
  437. callKeyUp(&eventData, [theEvent keyCode], mModifiers);
  438. }
  439. }
  440. - (void)flagsChanged:(NSEvent *)theEvent
  441. {
  442. NativeKeyEventData eventData = extractKeyDataFromModifierEvent(theEvent);
  443. mModifiers = [theEvent modifierFlags];
  444. callModifier([theEvent modifierFlags]);
  445. NSInteger mask = 0;
  446. switch([theEvent keyCode])
  447. {
  448. case 56:
  449. mask = NSShiftKeyMask;
  450. break;
  451. case 58:
  452. mask = NSAlternateKeyMask;
  453. break;
  454. case 59:
  455. mask = NSControlKeyMask;
  456. break;
  457. default:
  458. return;
  459. }
  460. if (mModifiers & mask)
  461. {
  462. eventData.mKeyEvent = NativeKeyEventData::KEYDOWN;
  463. callKeyDown(&eventData, [theEvent keyCode], 0);
  464. }
  465. else
  466. {
  467. eventData.mKeyEvent = NativeKeyEventData::KEYUP;
  468. callKeyUp(&eventData, [theEvent keyCode], 0);
  469. }
  470. }
  471. - (BOOL) acceptsFirstResponder
  472. {
  473. return YES;
  474. }
  475. - (NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender
  476. {
  477. NSPasteboard *pboard;
  478. NSDragOperation sourceDragMask;
  479. sourceDragMask = [sender draggingSourceOperationMask];
  480. pboard = [sender draggingPasteboard];
  481. if ([[pboard types] containsObject:NSURLPboardType])
  482. {
  483. if (sourceDragMask & NSDragOperationLink) {
  484. NSURL *fileUrl = [[pboard readObjectsForClasses:[NSArray arrayWithObject:[NSURL class]] options:[NSDictionary dictionary]] objectAtIndex:0];
  485. mLastDraggedUrl = [[fileUrl absoluteString] UTF8String];
  486. return NSDragOperationLink;
  487. }
  488. }
  489. return NSDragOperationNone;
  490. }
  491. - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
  492. {
  493. callHandleDragUpdated(mLastDraggedUrl);
  494. return NSDragOperationLink;
  495. }
  496. - (void) draggingExited:(id<NSDraggingInfo>)sender
  497. {
  498. callHandleDragExited(mLastDraggedUrl);
  499. }
  500. - (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender
  501. {
  502. return YES;
  503. }
  504. - (BOOL) performDragOperation:(id<NSDraggingInfo>)sender
  505. {
  506. callHandleDragDropped(mLastDraggedUrl);
  507. return true;
  508. }
  509. - (BOOL)hasMarkedText
  510. {
  511. return mHasMarkedText;
  512. }
  513. - (NSRange)markedRange
  514. {
  515. int range[2];
  516. getPreeditMarkedRange(&range[0], &range[1]);
  517. return NSMakeRange(range[0], range[1]);
  518. }
  519. - (NSRange)selectedRange
  520. {
  521. int range[2];
  522. getPreeditSelectionRange(&range[0], &range[1]);
  523. return NSMakeRange(range[0], range[1]);
  524. }
  525. - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
  526. {
  527. // Apple says aString can be either an NSString or NSAttributedString instance.
  528. // But actually it's NSConcreteMutableAttributedString or __NSCFConstantString.
  529. // I observed aString was __NSCFConstantString only aString was null string(zero length).
  530. // Apple also says when aString is an NSString object,
  531. // the receiver is expected to render the marked text with distinguishing appearance.
  532. // So I tried to make attributedStringInfo, but it won't be used... (Pell Smit)
  533. if (mMarkedTextAllowed)
  534. {
  535. unsigned int selected[2] = {
  536. unsigned(selectedRange.location),
  537. unsigned(selectedRange.length)
  538. };
  539. unsigned int replacement[2] = {
  540. unsigned(replacementRange.location),
  541. unsigned(replacementRange.length)
  542. };
  543. int string_length = [aString length];
  544. unichar text[string_length];
  545. attributedStringInfo segments;
  546. // I used 'respondsToSelector:@selector(string)'
  547. // to judge aString is an attributed string or not.
  548. if ([aString respondsToSelector:@selector(string)])
  549. {
  550. // aString is attibuted
  551. [[aString string] getCharacters:text range:NSMakeRange(0, string_length)];
  552. segments = getSegments((NSAttributedString *)aString);
  553. }
  554. else
  555. {
  556. // aString is not attributed
  557. [aString getCharacters:text range:NSMakeRange(0, string_length)];
  558. segments.seg_lengths.push_back(string_length);
  559. segments.seg_standouts.push_back(true);
  560. }
  561. setMarkedText(text, selected, replacement, string_length, segments);
  562. if (string_length > 0)
  563. {
  564. mHasMarkedText = TRUE;
  565. mMarkedTextLength = string_length;
  566. }
  567. else
  568. {
  569. // we must clear the marked text when aString is null.
  570. [self unmarkText];
  571. }
  572. }
  573. else
  574. {
  575. if (mHasMarkedText)
  576. {
  577. [self unmarkText];
  578. }
  579. }
  580. }
  581. - (void)commitCurrentPreedit
  582. {
  583. if (mHasMarkedText)
  584. {
  585. if ([[self inputContext] respondsToSelector:@selector(commitEditing)])
  586. {
  587. [[self inputContext] commitEditing];
  588. }
  589. }
  590. }
  591. - (void)unmarkText
  592. {
  593. [[self inputContext] discardMarkedText];
  594. resetPreedit();
  595. mHasMarkedText = FALSE;
  596. }
  597. // We don't support attributed strings.
  598. - (NSArray *)validAttributesForMarkedText
  599. {
  600. return [NSArray array];
  601. }
  602. // See above.
  603. - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
  604. {
  605. return nil;
  606. }
  607. - (void)insertText:(id)insertString
  608. {
  609. if (insertString != nil)
  610. {
  611. [self insertText:insertString replacementRange:NSMakeRange(0, [insertString length])];
  612. }
  613. }
  614. - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
  615. {
  616. if (!mHasMarkedText)
  617. {
  618. for (NSInteger i = 0; i < [aString length]; i++)
  619. {
  620. callUnicodeCallback([aString characterAtIndex:i], mModifiers);
  621. }
  622. }
  623. else
  624. {
  625. resetPreedit();
  626. // We may never get this point since unmarkText may be called before insertText ever gets called once we submit our text.
  627. // But just in case...
  628. for (NSInteger i = 0; i < [aString length]; i++)
  629. {
  630. handleUnicodeCharacter([aString characterAtIndex:i]);
  631. }
  632. mHasMarkedText = FALSE;
  633. }
  634. }
  635. - (void) insertNewline:(id)sender
  636. {
  637. if (!(mModifiers & NSCommandKeyMask) &&
  638. !(mModifiers & NSShiftKeyMask) &&
  639. !(mModifiers & NSAlternateKeyMask))
  640. {
  641. callUnicodeCallback(13, 0);
  642. }
  643. else
  644. {
  645. callUnicodeCallback(13, mModifiers);
  646. }
  647. }
  648. - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint
  649. {
  650. return NSNotFound;
  651. }
  652. - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
  653. {
  654. float pos[4] = {0, 0, 0, 0};
  655. getPreeditLocation(pos, mMarkedTextLength);
  656. return NSMakeRect(pos[0], pos[1], pos[2], pos[3]);
  657. }
  658. - (void)doCommandBySelector:(SEL)aSelector
  659. {
  660. if (aSelector == @selector(insertNewline:))
  661. {
  662. [self insertNewline:self];
  663. }
  664. }
  665. - (BOOL)drawsVerticallyForCharacterAtIndex:(NSUInteger)charIndex
  666. {
  667. return NO;
  668. }
  669. - (void) allowMarkedTextInput:(bool)allowed
  670. {
  671. mMarkedTextAllowed = allowed;
  672. }
  673. @end
  674. @implementation LLUserInputWindow
  675. - (void) close
  676. {
  677. [self orderOut:self];
  678. }
  679. @end
  680. @implementation LLNonInlineTextView
  681. /* Input Window is a legacy of 20 century, so we want to remove related classes.
  682. But unfortunately, Viwer web browser has no support for modern inline input,
  683. we need to leave these classes...
  684. We will be back to get rid of Input Window after fixing viewer web browser.
  685. How Input Window should work:
  686. 1) Input Window must not be empty.
  687. It must close when it become empty result of edithing.
  688. 2) Input Window must not close when it still has input data.
  689. It must keep open user types next char before commit. by Pell Smit
  690. */
  691. - (void) setGLView:(LLOpenGLView *)view
  692. {
  693. glview = view;
  694. }
  695. - (void)keyDown:(NSEvent *)theEvent
  696. {
  697. // mKeyPressed is used later to determine whethere Input Window should close or not
  698. mKeyPressed = [[theEvent charactersIgnoringModifiers] characterAtIndex:0];
  699. // setMarkedText and insertText is called indirectly from inside keyDown: method
  700. [super keyDown:theEvent];
  701. }
  702. // setMarkedText: is called for incomplete input(on the way to conversion).
  703. - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
  704. {
  705. [super setMarkedText:aString selectedRange:selectedRange replacementRange:replacementRange];
  706. if ([aString length] == 0) // this means Input Widow becomes empty
  707. {
  708. [self.window orderOut:self.window]; // Close this to avoid empty Input Window
  709. }
  710. }
  711. // insertText: is called for inserting commited text.
  712. // There are two ways to be called here:
  713. // a) explicitly commited (must close)
  714. // In case of user typed commit key(usually return key) or delete key or something
  715. // b) automatically commited (must not close)
  716. // In case of user typed next letter after conversion
  717. - (void) insertText:(id)aString replacementRange:(NSRange)replacementRange
  718. {
  719. [[self inputContext] discardMarkedText];
  720. [self setString:@""];
  721. [glview insertText:aString replacementRange:replacementRange];
  722. if (mKeyPressed == NSEnterCharacter ||
  723. mKeyPressed == NSBackspaceCharacter ||
  724. mKeyPressed == NSTabCharacter ||
  725. mKeyPressed == NSNewlineCharacter ||
  726. mKeyPressed == NSCarriageReturnCharacter ||
  727. mKeyPressed == NSDeleteCharacter ||
  728. (mKeyPressed >= 0xF700 && mKeyPressed <= 0xF8FF))
  729. {
  730. // this is case a) of above comment
  731. [self.window orderOut:self.window]; // to avoid empty Input Window
  732. }
  733. }
  734. @end
  735. @implementation LLNSWindow
  736. - (id) init
  737. {
  738. return self;
  739. }
  740. - (NSPoint)convertToScreenFromLocalPoint:(NSPoint)point relativeToView:(NSView *)view
  741. {
  742. NSScreen *currentScreen = [NSScreen currentScreenForMouseLocation];
  743. if(currentScreen)
  744. {
  745. NSPoint windowPoint = [view convertPoint:point toView:nil];
  746. NSPoint screenPoint = [[view window] convertBaseToScreen:windowPoint];
  747. NSPoint flippedScreenPoint = [currentScreen flipPoint:screenPoint];
  748. flippedScreenPoint.y += [currentScreen frame].origin.y;
  749. return flippedScreenPoint;
  750. }
  751. return NSZeroPoint;
  752. }
  753. - (NSPoint)flipPoint:(NSPoint)aPoint
  754. {
  755. return NSMakePoint(aPoint.x, self.frame.size.height - aPoint.y);
  756. }
  757. - (BOOL) becomeFirstResponder
  758. {
  759. callFocus();
  760. return true;
  761. }
  762. - (BOOL) resignFirstResponder
  763. {
  764. callFocusLost();
  765. return true;
  766. }
  767. - (BOOL)windowShouldClose:(NSWindow *)sender;
  768. {
  769. handleQuit();
  770. return NO;
  771. }
  772. - (void) close
  773. {
  774. callQuitHandler();
  775. }
  776. @end