]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/backend/cocoa/views/views.factor
cocoa inline input using IM
[factor.git] / basis / ui / backend / cocoa / views / views.factor
1 ! Copyright (C) 2006, 2010 Slava Pestov
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.c-types alien.data alien.strings
4 arrays assocs classes cocoa cocoa.application cocoa.classes
5 cocoa.pasteboard cocoa.runtime cocoa.subclassing cocoa.touchbar
6 cocoa.types cocoa.views combinators core-foundation.strings
7 core-graphics core-graphics.types core-text io.encodings.utf8
8 kernel literals locals math math.order math.parser
9 math.rectangles namespaces opengl sequences splitting threads
10 ui.commands ui.gadgets ui.gadgets.private ui.gadgets.worlds
11 ui.gestures ui.private words sorting math.vectors
12 ui.baseline-alignment ui.gadgets.line-support
13 ui.gadgets.editors ui.backend.cocoa.input-methods
14 ui.backend.cocoa.input-methods.editors io.encodings.utf16n
15 io.encodings.string classes.struct ;
16 IN: ui.backend.cocoa.views
17
18 : send-mouse-moved ( view event -- )
19     [ mouse-location ] [ drop window ] 2bi
20     [ move-hand fire-motion yield ] [ drop ] if* ;
21
22 ! Issue #1453
23 : button ( event -- n )
24     ! Cocoa -> Factor UI button mapping
25     -> buttonNumber {
26         { 0 [ 1 ] }
27         { 1 [ 3 ] }
28         { 2 [ 2 ] }
29         [ ]
30     } case ;
31
32 CONSTANT: NSAlphaShiftKeyMask 0x10000
33 CONSTANT: NSShiftKeyMask      0x20000
34 CONSTANT: NSControlKeyMask    0x40000
35 CONSTANT: NSAlternateKeyMask  0x80000
36 CONSTANT: NSCommandKeyMask    0x100000
37 CONSTANT: NSNumericPadKeyMask 0x200000
38 CONSTANT: NSHelpKeyMask       0x400000
39 CONSTANT: NSFunctionKeyMask   0x800000
40
41 CONSTANT: modifiers {
42         { S+ $ NSShiftKeyMask }
43         { C+ $ NSControlKeyMask }
44         { A+ $ NSCommandKeyMask }
45         { M+ $ NSAlternateKeyMask }
46     }
47
48 CONSTANT: key-codes
49     H{
50         { 71 "CLEAR" }
51         { 36 "RET" }
52         { 76 "ENTER" }
53         { 53 "ESC" }
54         { 48 "TAB" }
55         { 51 "BACKSPACE" }
56         { 115 "HOME" }
57         { 117 "DELETE" }
58         { 119 "END" }
59         { 122 "F1" }
60         { 120 "F2" }
61         { 99 "F3" }
62         { 118 "F4" }
63         { 96 "F5" }
64         { 97 "F6" }
65         { 98 "F7" }
66         { 100 "F8" }
67         { 123 "LEFT" }
68         { 124 "RIGHT" }
69         { 125 "DOWN" }
70         { 126 "UP" }
71         { 116 "PAGE_UP" }
72         { 121 "PAGE_DOWN" }
73     }
74
75 : key-code ( event -- string ? )
76     dup -> keyCode key-codes at
77     [ t ] [ -> charactersIgnoringModifiers CF>string f ] ?if ;
78
79 : event-modifiers ( event -- modifiers )
80     -> modifierFlags modifiers modifier ;
81
82 : key-event>gesture ( event -- modifiers keycode action? )
83     [ event-modifiers ] [ key-code ] bi ;
84
85 : send-key-event ( view gesture -- )
86     swap window [ propagate-key-gesture ] [ drop ] if* ;
87
88 : interpret-key-event ( view event -- )
89     NSArray swap -> arrayWithObject: -> interpretKeyEvents: ;
90
91 : send-key-down-event ( view event -- )
92     [ key-event>gesture <key-down> send-key-event ]
93     [ interpret-key-event ]
94     2bi ;
95
96 : send-key-up-event ( view event -- )
97     key-event>gesture <key-up> send-key-event ;
98
99 : mouse-event>gesture ( event -- modifiers button )
100     [ event-modifiers ] [ button ] bi ;
101
102 : send-button-down$ ( view event -- )
103     [ nip mouse-event>gesture <button-down> ]
104     [ mouse-location ]
105     [ drop window ]
106     2tri
107     [ send-button-down ] [ 2drop ] if* ;
108
109 : send-button-up$ ( view event -- )
110     [ nip mouse-event>gesture <button-up> ]
111     [ mouse-location ]
112     [ drop window ]
113     2tri
114     [ send-button-up ] [ 2drop ] if* ;
115
116 : send-scroll$ ( view event -- )
117     [ nip [ -> deltaX ] [ -> deltaY ] bi [ neg ] bi@ 2array ]
118     [ mouse-location ]
119     [ drop window ]
120     2tri
121     [ send-scroll ] [ 2drop ] if* ;
122
123 : send-action$ ( view event gesture -- )
124     [ drop window ] dip over [ send-action ] [ 2drop ] if ;
125
126 : add-resize-observer ( observer object -- )
127     [
128         "updateFactorGadgetSize:"
129         "NSViewFrameDidChangeNotification" <NSString>
130     ] dip add-observer ;
131
132 : string-or-nil? ( NSString -- ? )
133     [ CF>string NSStringPboardType = ] [ t ] if* ;
134
135 : valid-service? ( gadget send-type return-type -- ? )
136     2dup [ string-or-nil? ] [ string-or-nil? ] bi* and
137     [ drop [ gadget-selection? ] [ drop t ] if ] [ 3drop f ] if ;
138
139 : NSRect>rect ( NSRect world -- rect )
140     [ [ [ CGRect-x ] [ CGRect-y ] bi ] [ dim>> second ] bi* swap - 2array ]
141     [ drop [ CGRect-w ] [ CGRect-h ] bi 2array ]
142     2bi <rect> ;
143
144 : rect>NSRect ( rect world -- NSRect )
145     [ [ loc>> first2 ] [ dim>> second ] bi* swap - ]
146     [ drop dim>> first2 ]
147     2bi <CGRect> ;
148
149 CONSTANT: selector>action H{
150     { "undo:" undo-action }
151     { "redo:" redo-action }
152     { "cut:" cut-action }
153     { "copy:" copy-action }
154     { "paste:" paste-action }
155     { "delete:" delete-action }
156     { "selectAll:" select-all-action }
157     { "newDocument:" new-action }
158     { "openDocument:" open-action }
159     { "saveDocument:" save-action }
160     { "saveDocumentAs:" save-as-action }
161     { "revertDocumentToSaved:" revert-action }
162 }
163
164 : validate-action ( world selector -- ? validated? )
165     selector>action at
166     [ swap world-focus parents-handle-gesture? t ] [ drop f f ] if* ;
167
168 : touchbar-commands ( -- commands/f gadget )
169     world get-global [
170         children>> [
171             class-of "commands" word-prop
172             "touchbar" of dup [ commands>> ] when
173         ] map-find
174     ] [ f f ] if* ;
175
176 TUPLE: send-touchbar-command target command ;
177
178 M: send-touchbar-command send-queued-gesture
179     [ target>> ] [ command>> ] bi invoke-command ;
180
181 : touchbar-invoke-command ( n -- )
182     [ touchbar-commands ] dip over [
183         rot nth second
184         send-touchbar-command queue-gesture notify-ui-thread
185         yield
186     ] [ 3drop ] if ;
187
188 CONSTANT: NSNotFound 9223372036854775807 inline
189
190 IMPORT: NSAttributedString
191
192 <PRIVATE
193
194 :: >codepoint-index ( str utf16-index -- codepoint-index )
195     0 utf16-index 2 * str utf16n encode subseq utf16n decode length ;
196
197 :: >utf16-index ( str codepoint-index -- utf16-index )
198     0 codepoint-index str subseq utf16n encode length 2 / >integer ;
199
200 :: earlier-caret/mark ( editor -- loc )
201     editor editor-caret :> caret
202     editor editor-mark :> mark
203     caret first mark first = [
204         caret second mark second < [ caret ] [ mark ] if
205     ] [
206         caret first mark first < [ caret ] [ mark ] if
207     ] if ;
208
209 :: make-preedit-underlines ( gadget text range -- underlines )
210     f gadget preedit-selection-mode?<<
211     { } clone :> underlines!
212     text -> length :> text-length
213     0 0 <NSRange> :> effective-range
214     text -> string CF>string :> str
215     str utf16n encode :> byte-16n
216     0 :> cp-loc!    
217     "NSMarkedClauseSegment" <NSString> :> segment-attr
218     [ effective-range [ location>> ] [ length>> ] bi + text-length < ] [
219         text
220         segment-attr
221         effective-range [ location>> ] [ length>> ] bi +
222         effective-range >c-ptr
223         -> attribute:atIndex:effectiveRange: drop
224         1 :> thickness!
225         range location>> effective-range location>> = [
226             2 thickness!
227             t gadget preedit-selection-mode?<<
228         ] when
229         underlines
230         effective-range [ location>> ] [ length>> ] bi over +
231         [ str swap >codepoint-index ] bi@ swap - :> len
232         cp-loc cp-loc len + dup cp-loc!
233         2array thickness 2array
234         suffix underlines! 
235     ] while 
236     underlines length 1 = [
237         underlines first first 2 2array 1array  ! thickness: 2
238     ] [ underlines ] if ;
239
240 :: update-marked-text ( gadget str range -- )
241     gadget preedit? [
242         gadget remove-preedit-text
243     ] when
244     gadget earlier-caret/mark dup
245     gadget preedit-start<<
246     0 str length 2array v+ gadget preedit-end<<
247     str gadget temp-im-input drop
248     gadget preedit-start>>
249     0 str range location>> >codepoint-index
250     2array v+
251     dup gadget preedit-selected-start<<
252     0
253     range location>> dup range length>> + [ 2 * ] bi@
254     str utf16n encode subseq utf16n decode length
255     2array v+
256     dup gadget preedit-selected-end<<
257     dup gadget set-caret gadget set-mark                    
258     gadget preedit-start>> gadget preedit-end>> = [
259         gadget remove-preedit-info 
260     ] when ;
261
262 PRIVATE>
263
264 <CLASS: FactorView < NSOpenGLView
265     COCOA-PROTOCOL: NSTextInputClient
266
267     METHOD: void prepareOpenGL [
268
269         self SEL: setWantsBestResolutionOpenGLSurface:
270         -> respondsToSelector: c-bool> [
271
272             self 1 { void { id SEL char } } ?-> setWantsBestResolutionOpenGLSurface:
273
274             self { double { id SEL } } ?-> backingScaleFactor
275
276             dup 1.0 > [
277                 gl-scale-factor set-global t retina? set-global
278                 cached-lines get-global clear-assoc
279             ] [ drop ] if
280
281             self -> update
282         ] when
283     ] ;
284
285     ! TouchBar
286     METHOD: void touchBarCommand0 [ 0 touchbar-invoke-command ] ;
287     METHOD: void touchBarCommand1 [ 1 touchbar-invoke-command ] ;
288     METHOD: void touchBarCommand2 [ 2 touchbar-invoke-command ] ;
289     METHOD: void touchBarCommand3 [ 3 touchbar-invoke-command ] ;
290     METHOD: void touchBarCommand4 [ 4 touchbar-invoke-command ] ;
291     METHOD: void touchBarCommand5 [ 5 touchbar-invoke-command ] ;
292     METHOD: void touchBarCommand6 [ 6 touchbar-invoke-command ] ;
293     METHOD: void touchBarCommand7 [ 7 touchbar-invoke-command ] ;
294
295     METHOD: id makeTouchBar [
296         touchbar-commands drop [
297             length 8 min <iota> [ number>string ] map
298         ] [ { } ] if* self make-touchbar
299     ] ;
300
301     METHOD: id touchBar: id touchbar makeItemForIdentifier: id string [
302         touchbar-commands drop [
303             [ self string CF>string dup string>number ] dip nth
304             second name>> "com-" ?head drop over
305             "touchBarCommand" prepend make-NSTouchBar-button
306         ] [ f ] if*
307     ] ;
308
309     ! Rendering
310     METHOD: void drawRect: NSRect rect [ self window [ draw-world ] when* ] ;
311
312     ! Events
313     METHOD: char acceptsFirstMouse: id event [ 0 ] ;
314
315     METHOD: void mouseEntered: id event [ self event send-mouse-moved ] ;
316
317     METHOD: void mouseExited: id event [ forget-rollover ] ;
318
319     METHOD: void mouseMoved: id event [ self event send-mouse-moved ] ;
320
321     METHOD: void mouseDragged: id event [ self event send-mouse-moved ] ;
322
323     METHOD: void rightMouseDragged: id event [ self event send-mouse-moved ] ;
324
325     METHOD: void otherMouseDragged: id event [ self event send-mouse-moved ] ;
326
327     METHOD: void mouseDown: id event [ self event send-button-down$ ] ;
328
329     METHOD: void mouseUp: id event [ self event send-button-up$ ] ;
330
331     METHOD: void rightMouseDown: id event [ self event send-button-down$ ] ;
332
333     METHOD: void rightMouseUp: id event [ self event send-button-up$ ] ;
334
335     METHOD: void otherMouseDown: id event [ self event send-button-down$ ] ;
336
337     METHOD: void otherMouseUp: id event [ self event send-button-up$ ] ;
338
339     METHOD: void scrollWheel: id event [ self event send-scroll$ ] ;
340
341     METHOD: void keyDown: id event [ self event send-key-down-event ] ;
342
343     METHOD: void keyUp: id event [ self event send-key-up-event ] ;
344
345     METHOD: char validateUserInterfaceItem: id event
346     [
347         self window [
348             event -> action utf8 alien>string validate-action
349             [ >c-bool ] [ drop self event SUPER-> validateUserInterfaceItem: ] if
350         ] [ 0 ] if*
351     ] ;
352
353     METHOD: void undo: id event [ self event undo-action send-action$ ] ;
354
355     METHOD: void redo: id event [ self event redo-action send-action$ ] ;
356
357     METHOD: void cut: id event [ self event cut-action send-action$ ] ;
358
359     METHOD: void copy: id event [ self event copy-action send-action$ ] ;
360
361     METHOD: void paste: id event [ self event paste-action send-action$ ] ;
362
363     METHOD: void delete: id event [ self event delete-action send-action$ ] ;
364
365     METHOD: void selectAll: id event [ self event select-all-action send-action$ ] ;
366
367     METHOD: void newDocument: id event [ self event new-action send-action$ ] ;
368
369     METHOD: void openDocument: id event [ self event open-action send-action$ ] ;
370
371     METHOD: void saveDocument: id event [ self event save-action send-action$ ] ;
372
373     METHOD: void saveDocumentAs: id event [ self event save-as-action send-action$ ] ;
374
375     METHOD: void revertDocumentToSaved: id event [ self event revert-action send-action$ ] ;
376
377     ! Multi-touch gestures
378     METHOD: void magnifyWithEvent: id event
379     [
380         self event
381         dup -> deltaZ sgn {
382             {  1 [ zoom-in-action send-action$ ] }
383             { -1 [ zoom-out-action send-action$ ] }
384             {  0 [ 2drop ] }
385         } case
386     ] ;
387
388     METHOD: void swipeWithEvent: id event
389     [
390         self event
391         dup -> deltaX sgn {
392             {  1 [ left-action send-action$ ] }
393             { -1 [ right-action send-action$ ] }
394             {  0
395                 [
396                     dup -> deltaY sgn {
397                         {  1 [ up-action send-action$ ] }
398                         { -1 [ down-action send-action$ ] }
399                         {  0 [ 2drop ] }
400                     } case
401                 ]
402             }
403         } case
404     ] ;
405
406     METHOD: char acceptsFirstResponder [ 1 ] ;
407
408     ! Services
409     METHOD: id validRequestorForSendType: id sendType returnType: id returnType
410     [
411         ! We return either self or nil
412         self window [
413             world-focus sendType returnType
414             valid-service? [ self ] [ f ] if
415         ] [ f ] if*
416     ] ;
417
418     METHOD: char writeSelectionToPasteboard: id pboard types: id types
419     [
420         NSStringPboardType types CF>string-array member? [
421             self window [
422                 world-focus gadget-selection
423                 [ pboard set-pasteboard-string 1 ] [ 0 ] if*
424             ] [ 0 ] if*
425         ] [ 0 ] if
426     ] ;
427
428     METHOD: char readSelectionFromPasteboard: id pboard
429     [
430         self window :> window
431         window [
432             pboard pasteboard-string
433             [ window user-input 1 ] [ 0 ] if*
434         ] [ 0 ] if
435     ] ;
436
437     ! Text input
438     METHOD: void insertText: id text replacementRange: NSRange replacementRange [
439             self window :> window
440             window [
441                 "" clone :> str!
442                 text NSString -> class -> isKindOfClass: 0 = not [
443                     text CF>string str!               
444                 ] [
445                     text -> string CF>string str!               
446                 ] if
447                 window world-focus :> gadget
448                 gadget support-input-methods? [
449                     gadget preedit? [
450                         gadget [ remove-preedit-text ] [ remove-preedit-info ] bi
451                     ] when
452                     str gadget user-input* drop                    
453                     f gadget preedit-selection-mode?<<
454                 ] [ 
455                     str window user-input
456                 ] if
457             ] when
458         ] ;
459     
460     METHOD: char hasMarkedText [
461             self window :> window
462             window [
463                 window world-focus :> gadget
464                 gadget preedit? [ 1 ] [ 0 ] if
465             ] [ 0 ] if
466         ] ;
467
468     METHOD: NSRange markedRange [ 
469             self window :> window
470             window [
471                 window world-focus :> gadget
472                 gadget preedit? [
473                     gadget [ preedit-start>> second ] [ preedit-end>> second ] bi >= [ 
474                         NSNotFound 0 
475                     ] [
476                         gadget preedit-start>> first gadget editor-line :> str
477                         str gadget preedit-start>> second >utf16-index dup  ! location
478                         str gadget preedit-end>> second >utf16-index swap - ! length
479                     ] if
480                 ] [  NSNotFound 0 ] if
481             ] [ NSNotFound 0 ] if
482             <NSRange>
483         ] ;
484
485     METHOD: NSRange selectedRange [
486             self window :> window
487             window [
488                 window world-focus :> gadget
489                 gadget support-input-methods? [
490                     gadget preedit? [
491                         gadget preedit-start>> first gadget editor-line :> str
492                         str
493                         gadget
494                         [ preedit-selected-start>> second ]
495                         [ preedit-start>> second ] bi - >utf16-index              ! location
496                         str gadget preedit-selected-end>> second >utf16-index
497                         str gadget preedit-selected-start>> second >utf16-index - ! length
498                     ] [ gadget earlier-caret/mark second 0 ] if
499                 ] [ 0 0 ] if
500             ] [ 0 0 ] if 
501             <NSRange>
502         ] ;
503     
504     METHOD: void setMarkedText: id text selectedRange: NSRange selectedRange
505                                      replacementRange: NSRange replacementRange [           
506             self window :> window
507             { } clone :> underlines!
508             window [
509                 window world-focus :> gadget
510                 "" clone :> str!
511                 text NSString -> class -> isKindOfClass: 0 = not [
512                     text CF>string str!               
513                 ] [
514                     text -> string CF>string str!               
515                     gadget support-input-methods? [
516                         gadget text selectedRange make-preedit-underlines underlines!
517                     ] when
518                 ] if
519                 gadget support-input-methods? [
520                     gadget str selectedRange update-marked-text                   
521                     underlines gadget preedit-underlines<<
522                 ] when
523             ] when            
524         ] ;
525              
526     METHOD: void unmarkText [ 
527             self window :> window
528             window [
529                 window world-focus :> gadget
530                 gadget support-input-methods? [
531                     gadget preedit? [
532                         gadget {
533                             [ preedit-start>> second ]
534                             [ preedit-end>> second ]
535                             [ preedit-start>> first ] [ editor-line ]
536                         } cleave subseq
537                         gadget [ remove-preedit-text ] [ remove-preedit-info ] bi
538                         gadget user-input* drop
539                     ] when
540                     f gadget preedit-selection-mode?<<
541                 ] when
542             ] when
543         ] ;
544     
545     METHOD: id validAttributesForMarkedText [             
546             NSArray "NSMarkedClauseSegment" <NSString> -> arrayWithObject:
547         ] ;
548
549     METHOD: id attributedSubstringForProposedRange: NSRange range
550                                        actualRange: id actualRange [ f ] ;
551     
552     METHOD: NSUInteger characterIndexForPoint: NSPoint point [ 0 ] ;
553
554     METHOD: NSRect firstRectForCharacterRange: NSRange aRange
555                                   actualRange: id actualRange [
556             aRange :> range!
557             actualRange [
558                  actualRange NSRange memory>struct range!
559              ] when
560             
561             self window :> window
562             window [
563                 window world-focus preedit? [
564                     window world-focus :> gadget
565                     gadget editor-caret first gadget editor-line :> str                    
566                     str range location>> >codepoint-index :> start-pos
567                     gadget screen-loc                    
568                     gadget editor-caret first start-pos 2array gadget loc>x dup :> xl
569                     gadget caret-loc second gadget caret-dim second + 
570                     [ >fixnum ] bi@ 2array v+ { 1 -1 } v*
571                     window handle>> window>> dup -> frame -> contentRectForFrameRect:
572                     CGRect-top-left 2array v+
573                     first2 0 gadget line-height >fixnum
574                 ] [ 0 0 0 0 ] if
575             ] [ 0 0 0 0 ] if    
576             <CGRect>
577         ] ;
578         
579     ! Initialization
580     METHOD: void updateFactorGadgetSize: id notification
581     [
582         self window :> window
583         window [
584             self view-dim window dim<< yield
585         ] when
586     ] ;
587
588     METHOD: void doCommandBySelector: SEL selector [ ] ;
589
590     METHOD: id initWithFrame: NSRect frame pixelFormat: id pixelFormat
591     [
592         self frame pixelFormat SUPER-> initWithFrame:pixelFormat:
593         dup dup add-resize-observer
594     ] ;
595
596     METHOD: char isOpaque [ 0 ] ;
597
598     METHOD: void dealloc
599     [
600         self remove-observer
601         self SUPER-> dealloc
602     ] ;
603 ;CLASS>
604
605 : sync-refresh-to-screen ( GLView -- )
606     -> openGLContext -> CGLContextObj NSOpenGLCPSwapInterval 1 int <ref>
607     CGLSetParameter drop ;
608
609 : <FactorView> ( dim pixel-format -- view )
610     [ FactorView ] 2dip <GLView> [ sync-refresh-to-screen ] keep ;
611
612 : save-position ( world window -- )
613     -> frame CGRect-top-left 2array >>window-loc drop ;
614
615 <CLASS: FactorWindowDelegate < NSObject
616
617     METHOD: void windowDidMove: id notification
618     [
619         notification -> object -> contentView window
620         [ notification -> object save-position ] when*
621     ] ;
622
623     METHOD: void windowDidBecomeKey: id notification
624     [
625         notification -> object -> contentView window
626         [ focus-world ] when*
627     ] ;
628
629     METHOD: void windowDidResignKey: id notification
630     [
631         forget-rollover
632         notification -> object -> contentView :> view
633         view window :> window
634         window [
635             view -> isInFullScreenMode 0 =
636             [ window unfocus-world ] when
637         ] when
638     ] ;
639
640     METHOD: char windowShouldClose: id notification [ 1 ] ;
641
642     METHOD: void windowWillClose: id notification
643     [
644         notification -> object -> contentView
645         [ window ungraft ] [ unregister-window ] bi
646     ] ;
647
648     METHOD: void windowDidChangeBackingProperties: id notification
649     [
650
651         notification -> object dup SEL: backingScaleFactor
652         -> respondsToSelector: c-bool> [
653             { double { id SEL } } ?-> backingScaleFactor
654
655             [ [ 1.0 > ] keep f ? gl-scale-factor set-global ]
656             [ 1.0 > retina? set-global ] bi
657         ] [ drop ] if
658     ] ;
659 ;CLASS>
660
661 : install-window-delegate ( window -- )
662     FactorWindowDelegate install-delegate ;