-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathoutline.py
2935 lines (2732 loc) · 101 KB
/
outline.py
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
todo
====
- .. new:Wish list: a way to turn off (or on all checkboxes) and then Crete
outline elements with checkboxes.
In other words, provide a way that parts of the outline are tasks or todos with checkboxes but not necessarily all lines.
- .. bug: crash if open .content file see https://i.imgur.com/DoS38RI
- .. new: 2nd arg file = directory
- .. new: arg .ext => direct show list of files, which directory
- .. new: multiple level undo
- python check size of one data_source.items sys.getsizeof
- memo array of saved items + their action + index which is active
- quid if action = text or delete
- .. bug: support rotation of device while running
- .. bug: ...
- .. bug: scroll TableView while dragging does not work
in longpress, state 2, content_offset so red line in the middle of screen
works but locks and dragged box stays visible...
- .. new: support level 0 = [] > no outline
- doubletap on checkbox to get popup menu
- .. try: accelerate program
- redisp visible rows instead of reload_data
- except if del/add/move? if add at end, stupid
- show/hide
- check/uncheck
- ...
- ...
- .. new: drag with copy
- start how? popupmenu: move line with its children
- display moving box
- touch state = 1 = take it
- 2 = move it
- 3 = drop it copy without delete and remove box
- how to cancel it without drop: drop outside
- .. main menu: style => modif font,font_size, color for each level
- .. - memo not per line but per file in .content general, like format type
- .. functionnality to build/modify user format?
- .. - memo infos in .prm if detail modifiable
- .. - formats=tableview {item:type,accessorytype:detail} ou swipe avec user
- .. - explication: I->roman A->alpha 1.->n i-> a-> level+1
'''
import appex
import ast
import collections
import console
from datetime import datetime
import dialogs
import File_Picker # https://github.com/cvpe/Pythonista-scripts/blob/master/File_Picker.py
import Folder_Picker # https://github.com/cvpe/Pythonista-scripts/blob/master/Folder_Picker.py
from functools import partial
from gestures import *
import inspect
from math import isinf
from objc_util import *
import os
import re
from SetTextFieldPad import SetTextFieldPad # https://github.com/cvpe/Pythonista-scripts/blob/master/SetTextFieldPad.py
if not appex.is_running_extension():
import swizzle
import sys
import ui
import unicodedata
Version = 'V00.41'
Versions = '''
Version V00.41
- correction of bug "crash when closing settings option"
- support of extension passed as 1st argument
nb: - example: .txt will show all files grayed except .txt ones
Version V00.40
- support of file passed as 1st argument
nb: - only file in script folder is actually supported
- script checks file and its.content both exit
- ex url: pythonista3://MyFolder/outline?action=run&argv=a.txt
Version V00.39
- correction of bug "keyboard hides data entry of text in rows"
Version V00.38
- correction of bug "drop into the moving lines was allowed"
Version V00.37
- correction of bug "filter was reset to zero"
- support on iPhone kind of popover presentation via half transparent shield for:
- files menu tableview
- format types menu tableview
- search textfield
- font size textfield
- popup menu
- not needed for dialogs like settings and filter and for big views like versions
- force vertical popup menu on iPhone
Version V00.36
- support iPhone by using ui.Buttons instead of ui.ButtonItems for menu buttons
Version V00.35
- new options in popup menu to check or uncheck the tapped row and its children
Version V00.34
- new functionnality: filter
- new button in main menu
- allows to filter lines to show (other are hidden)
< level
= level
> level
Version V00.33
- correction of bug "local variable 'cell' reference before assign"
- correction of bug "move before first row does not work"
- correction of bug "move after last row does not work"
- correction of bug "cursor leaves search field and goes to a row at each char"
- long options of horizontal popup menu in two lines
nb: popup black menu has same height as before, the minimum allowed (40 pixels)
Version V00.32
- support "autocapitalization type (see ui.TextView doc)"
- new general setting
- use this setting when entering text (none, words, sentence, all)
Version V00.31
- correction of bug "undo did not work"
- correction of bug "move before first line did not work"
Version V00.30
- use a TableView instead of a TextView (full review)
- support delete row and its children option in popup menu
- support enter between words in text, stay in same outline
- modif infos stored in .log file easier reading
- for new file, do not ask folder and name before first save or at end
- without folder/file, no auto save is possible and title is ?
- an outline with multiple lines is saved with a blnk outline from the second
line so the text is visible and printable as is.
- On my iPad/iPhone now accessible if, and only if, you share ONCE a file
from this Files app folder to this program.
The path will be stored in .prm file.
- support "delete in red"
- new general setting
- display or not red background for "delete with children" option in popup menu
- support "single or double tap for popup menu"
- new general "setting"
- single or double tap on outline needed for popup menu
- support of redo after undo (same button, icon changes automatically)
Version V00.29
- support top folder also for folder_picker when creating a new file
- bad scrolling at typing normal characters solved in some cases,
but not all, bug still not identified...
Version V00.28
- support "Files"
- new general setting local, iCloud, on my iDevice, iCloud Drive
- if not accessible, segment will be disabled
- file picker on selected folder
Version V00.27
- correction of bug "auto-save parameter incorrect in .prm file"
- temporary workaround to scrolling problem: when typing in a line, automatic
scroll so this line is at top of screen and you don't have this annoying
scroll at each typed character. But this does not work each time. Weird
Version V00.26
- support "auto-save"
- new general setting no, each character typed, each line by CR, tab, back tab
nb: time of last save (in hh:mm:ss.ssss) is shown in settings screen
- save in function of setting and typing
- save will now
- delete .old files if they exist
- rename files into .old
- save files
Version V00.25
- correction of bug "predictive text may generate crash or doubled end characters"
- no more error message when you drop a box on its original area, used to cancel
- new file will use default font Menlo and default font size 18
- support clickable (short press) and underlined weblink
on all words (ending with a blank) beginning by http:// or https://
nb: be careful, url is case sensitive
- new option in Files popup menu: rename
- check actual file and its .content exist (not the case if new in progress)
- ask new name
- check renamed file and its .content do not already exist
- rename file and its content
Version V00.24
- default font size will be now 18
- no more alert if last open file, stored in .prm, does no exist anymore
- font and font_size saved in .content, so when file is open, they are known
- backtab on an outline of first level not allowed
Version V00.23
- correction of bug "paste text containing CR did lock the script"
- correction of bug "popup menu location incorrect if long text"
- outline showed in yellow in horizontal popup menu, to be sure
the menu is relative to the tapped outline
- new functionnality: undo
- new button in main menu
- shows name of action undoable in red on the button
- operational for undoing move (drag/drop)
- operational for undoing CR (linefeed)
- operational for undoing tab (demote)
- operational for undoing back (promote)
- disable if typed or deleted characters
Version V00.22
- correction of bug "if text bigger than one screen, any typing
automatically scrolls until end of file".
workaround found is to locate text row at edited line
- correction of bug "checkbox was not saved correctly in .content"
- correction of bug "checkboxes are being reset as soon as new item is typed"
Version V00.21
- correction of BIG (sorry) bug "hide/show icons were not synchronized with lines
when scrolling more than one screen"
- correction of bug "tap outside search field while it was not empty" does not
reshow all lines""
- support move left/right dragged box on its initial line to promote/demote
- support "show lines separator"
- new general setting
- display or not a line after each (not hidden) text line
- support "checkboxes"
- new general setting
- display or not a checkbox in front of (not hidden) line
- store checkbox per line in the .content file
Version V00.20
- review all renumbering (one more time)
Version V00.19
- correction of bug "log may not be activated after an 'open file'"
- correction of bug "move last line shows a too high pink area"
- correction of bug "bad renumbering after move"
- support new setting "font size of hidden outlines, may be set to 0"
- support longpress and double tap popup menu only on outline
- support standard gesture select/copy/paste only on text it-self
- differentiate if we would drop under the outline or under the text
by start the red line at left of outline or left of the text
- support drop under outline and under text
Version V00.18
- bugs
- correction of bug "bad renumbering after drop"
- correction of bug "crash 'tuple index out of range' if change outline type"
- correction of bug "crash if drop after a line without outline"
Version V00.17
- support "hide/show children via buttons at left of outline"
Version V00.16
- support "log"
- new general setting
- log each typed key
- play log typed keys
- log each move
- play log move
Version V00.15
- bugs
- correction of bug "long press on last lines shows full text as pink area"
Version V00.14
- bugs
- correction of bug "backtab on a line did not also backtab its children"
- correction of bug "drop after last line didn't do anything"
- full review for renumbering for
- "backtab"
Version V00.13
- bugs
- correction of bug "new file was saved as first use, even if not asked"
- correction of bug "enter in font size did not close the textfield"
- correction of bug "error 'list index out of range' at end of file"
- correction of bug "error 'list index out of range' in renumbering"
if last line has a CR"
- full review for renumbering for
- tab"
- "lf "
- "backtab" still in progress
- "dropped lines"
- "removed lines of dropped original"
- text in moving box will have same font and font size as TextView text
- support "show original area"
- new general setting
- display or no a coloured rectangle on the original dragged area
Version V00.12
- bugs
- full review of tab process and checks
- full review of backtab process and checks
- correction of bug "typing a tab or backtab before an outline was now allowed"
Version V00.11
- bugs
- correction of bug "characters insertion before an outline was allowed"
- correction of bug "CR before an outline was allowed"
- correction of bug "CR before a line without outline crashed"
- correction of bug "CR at begin of file before an outline was incorrect"
- support CR in the middle of a line, with renumbering of following lines
Version V00.10
- bugs
- correction of bug "tab crashes on replaceObjectsInRange out of bounds"
- correction of bug "incorrect renumbering lines after CR"
Version V00.09
- bugs
- correction of bug of crash when "drop before first line"
nb: new renumbering bug has appeared, not yet solved
- correction of bug of crash with "'Outliner' object has no attribute 'target'"
- correction of bug of hidden but identic (invisible) outlines do not have
the font size of hidden
- correction of bug of tapping outside textfield (font size, searched text)
closes the entire app
- correction of bug of same outlines (gray) do not have same font_size
as normal ones
- moving box
- will now contain coloured outlines
- the moving box was displayed above the finger position to allow to always
see where it would be inserted, but, at the top of the text, the box was
outside the screen, thus invisible. Now, this box will be drawn at right
of the finger.
- search in lines
- new main button for searching
- display an ui.TextField to enter the searched text
- display only lines containing the search text (case,accents non sensitive)
nb: displayed lines vary in real time
- press enter to close the TextField and come back to full display
- review .content file for future improvements like outline hidden, style etc...
Version V00.08
- no more blue dot at top/left of moving box
- new settings button in main menu
- support "popup menu orientation"
- new general setting
- support both vertical and horizontal orientations of popup menu
- bugs
- correction of bug of two successive tabs on same line
- support of drop
- check no drop of a box of text into it-self
- support of drop for move operation only
nb: draft process, several renumbering bugs subsist, be patient
- support of "force a new line with same outline"
- new general setting
- new option in popup menu
- with special icon if horizontal popup menu
- generates an outline, same as previous line
- no renumbering of next lines will occur
nb: long lines automatically (by ui.TextView) break and should generate a same outline on next line, but this is not yet supported.
Force same outline functionality may be a workaround
- support "same outline invisibility"
- new general setting
- support both invisible or light gray (tests) same outline
- begin of future (eventual) development for details of outline format types
- better parametrization of format types
- accessory info button in format types popup menu gives more details
Version V00.07
- popup menu was shown by tapping a line but this does no more allow to set
the cursor, thus replace tap by a double tap
- tap popup menu y-centered on the tapped line
- popup menu now horizontal in more standard aspect
- locally built icon for font size button
- locally built icon for font button
- correction of bug of cursor always set at end of text
- support outline bullets format
- height of outline format types menu computed in function of types number
- font size introduction via integer keyboard in popover TextField
Version V00.06
- moving box for dragging limited to text it contains
- during dragging, a red line indicates where the moving text would be inserted
- font button for font selection
- font size button for font size selection
- promote/demote by gestures:
- either by a long press on one line and moving the dragging box left or right
on the same line
- either by a left or right swipe on one line
Version V00.05
- remove the "move" option from the popup menu when tapping an outline
- to start a drag operation, long press anywhere on a line
- hold your finger on the screen
- pressed line and its children lines are set in a little mobile label
- this label is above your finger so it stays visible why moving your finger
- move the mobile label so its top/left blue point falls on a line
- drop process is still to be developped, wait and see
nb: actual drop process drops the entire text (outlines included)
at specified location
Version V00.04
- correction of bug of automatic renumbering after line feed
- correction of bug of automatic renumbering after tab
- correction of bug of automatic renumbering after back tab
- if outline is exactly the same as previous line, display it in gray
nb: - actually, this should not be authorized but automatic renumbering
sometimes generates such invalid cases
- if this functionnality is allowed, the outline would become invisible
- hide/show children supported (also saved for next run)
nb: actually, for testing, not really hidden but small characters to check
which lines would be hidden
Version V00.03
- at program end, outline.prm written with path and name of last edited file
- automatic open last edited file at program start
- automatic generation of first outline when new file
Version V00.02
- File Picker
- Folder Picker
- file open
- file save
- file new
- save levels and outline type in xxx.content
- when tab, check maximum level reached
- when change outline format, check maximum level reached
Version V00.01
- add row above keyboard with up/down outline level' keys
- differentiate up/down level keys of tab and left delete
- add Files button and its submenu, without any process
- checks: delete/cut selected mix of outline not allowed (message)
- allows "up level" key anywhere in the line
Version V00.00
- checks: editing outline is not allowed (message)
- checks: delete/cut selected mix of outline and normal characters
not allowed (message)
- checks: delete line feed followed by a line with an outline
not allowed (message)
- support normal characters
- support tab at begin of line with automatic outline
- support tab in text, simulate line feed keeping same (invisible) outline
- support line feed with automatic outline, only at end of text
- support delete/cut of normal characters, even lf (see checks)
- support coloured outline
- support outline color picker, even during editing
- support outline format change, even during editing
- support outline decimal format (not yet alignment and big numbers)
- support outline alphanumeric format (not yet alignment and big numbers)
- support outline traditional format (not yet alignment and big numbers)
- support versions button (ok, you have tested it, nice isn't it? 😀)
- support button on each outline for future actions (move?...)
'''
NSMutableAttributedString = ObjCClass('NSMutableAttributedString')
NSForegroundColorAttributeName = ns('NSColor')
UIColor = ObjCClass('UIColor')
UIFont = ObjCClass('UIFont')
NSFontAttributeName = ns('NSFont')
NSLinkAttributeName = ns('NSLink')
NSUnderlineStyleAttributeName = ns('NSUnderline')
font = UIFont.fontWithName_size_('Menlo', 18)
font_hidden = UIFont.fontWithName_size_('Menlo', 6)
SUIViewController = ObjCClass('SUIViewController')
UIFontPickerViewController = ObjCClass('UIFontPickerViewController')
UIFontPickerViewControllerConfiguration = ObjCClass('UIFontPickerViewControllerConfiguration')
pad_integer = [{'key':'1'},{'key':'2'},{'key':'3'},
{'key':'back space','icon':'typb:Delete'},
{'key':'new row'},
{'key':'4'},{'key':'5'},{'key':'6'},
#{'key':'delete','icon':'emj:Multiplication_X'},
{'key':'new row'},
{'key':'7'},{'key':'8'},{'key':'9'},
{'key':'new row'},
{'key':'nul'},{'key':'0'},{'key':'nul'},{'key':'⏎','SFicon':'return'}]
bs = '\b'
lf ='\n'
tab = '\t'
PY3 = sys.version_info[0] >= 3
if PY3:
basestring = str
def my_form_dialog(title='', fields=None, sections=None, done_button_title='Done', wd=500, hd=500):
# copy of dialogs.form_dialog
if not sections and not fields:
raise ValueError('sections or fields are required')
if not sections:
sections = [('', fields)]
if not isinstance(title, basestring):
raise TypeError('title must be a string')
for section in sections:
if not isinstance(section, collections.Sequence):
raise TypeError('Sections must be sequences (title, fields)')
if len(section) < 2:
raise TypeError('Sections must have 2 or 3 items (title, fields[, footer]')
if not isinstance(section[0], basestring):
raise TypeError('Section titles must be strings')
if not isinstance(section[1], collections.Sequence):
raise TypeError('Expected a sequence of field dicts')
for field in section[1]:
if not isinstance(field, dict):
raise TypeError('fields must be dicts')
cc = dialogs._FormDialogController(title, sections, done_button_title=done_button_title)
cc.container_view.frame = (0, 0, wd, hd)
cc.view.frame = (0, 0, wd, hd)
#==================== dialogs.form_dialog modification 1: begin
for i in range(0,len(cc.cells[0])): # loop on rows of section 0
cell = cc.cells[0][i] # ui.TableViewCell of row i
# some fields types are subviews of the cell:
# text,number,url,email,password,switch
# but check, date and time are not set as subviews of cell.content_view
if len(cell.content_view.subviews) > 0:
tf = cell.content_view.subviews[0] # ui.TextField of value in row
# attention: tf.name not set for date fields
item = cc.sections[0][1][i] # section 0, 1=items, row i
if 'segmented' in tf.name:
segmented = ui.SegmentedControl()
segmented.name = cell.text_label.text
segmented.frame = tf.frame
segmented.width = 240
segmented.x = cc.view.width - segmented.width-10 # cc.view is tableview
segmented.segments = item['segments']
value = item.get('value', '')
segmented.selected_index = item['segments'].index(value)
cell.content_view.remove_subview(tf)
del cc.values[tf.name]
del tf
cell.content_view.add_subview(segmented)
# multiline segments
for sv in ObjCInstance(segmented).subviews():
if sv._get_objc_classname().startswith(b'UISegmentedControl'):
if 'accessible' in item:
accessible = item['accessible']
for i in range(len(accessible)):
#print(item['segments'][i],accessible[i])
if not accessible[i]:
sv.setEnabled_forSegmentAtIndex_(False,i)
for ssv in sv.subviews():
if ssv._get_objc_classname().startswith(b'UISegment'):
ssv.label().numberOfLines = 0
ssv.label().adjustsFontSizeToFitWidth = True # auto resize font to fit
elif isinstance(tf, ui.TextField):
#print(tf.name)
#tf.item = item # if needed during checks
tf.alignment=ui.ALIGN_RIGHT
tf.bordered = True
tf.font = ('Menlo',16)
tf.flex = ''
h = cell.content_view.height
if 'pad' in item:
SetTextFieldPad(tf, pad=item['pad'], textfield_did_change=cc.textfield_did_change)
w = 80
tf.frame = (cc.view.width-w-10,(h-20)/2,w,20)
#==================== dialogs.form_dialog modification 1: end
cc.container_view.present('sheet')
cc.container_view.wait_modal()
# Get rid of the view to avoid a retain cycle:
cc.container_view = None
if cc.was_canceled:
return None
#==================== dialogs.form_dialog modification 2: begin
for i in range(0,len(cc.cells[0])): # loop on rows of section 0
cell = cc.cells[0][i] # ui.TableViewCell of row i
# some fields types are subviews of the cell:
# text,number,url,email,password,switch
# but check, date and time are not set as subviews of cell.content_view
for tf in cell.content_view.subviews:
if 'SegmentedControl' in str(type(tf)):
item = cc.sections[0][1][i] # section 0, 1=items, row i
if tf.selected_index >= 0:
cc.values[tf.name] = item['segments'][tf.selected_index]
#==================== dialogs.form_dialog modification 2: end
return cc.values
#==================== copied from dialogs: end
def fontPickerViewControllerDidPickFont_(_self, _cmd, _controller):
global mv
controller = ObjCInstance(_controller)
font = str(controller.selectedFontDescriptor().objectForKey_('NSFontFamilyAttribute'))
mv.set_font(font_type=font)
PickerDelegate = create_objc_class(
'PickerDelegate',
methods=[fontPickerViewControllerDidPickFont_],
protocols=['UIFontPickerViewControllerDelegate']
)
class MyInputAccessoryView(ui.View):
def __init__(self, row, *args, **kwargs):
#super().__init__(self, *args, **kwargs)
self.row = row
self.width = ui.get_screen_size()[0] # width of keyboard = screen
self.background_color = 'lightgray'#(0,1,0,0.2)
d = 4
hb = 44
self.height = 2*d + hb
self.pad = [
{'key':'tab','data':'\x01', 'sf':'text.chevron.right', 'x':10},
{'key':'shift-tab','data':'\x02', 'sf':'text.chevron.left', 'x':self.width-10-hb}
]
# build buttons
for pad_elem in self.pad:
button = ui.Button() # Button for user functionnality
button.frame = (int(pad_elem['x']),d,hb,hb)
button.name = pad_elem['key']
button.background_color = 'white' # or any other color
button.tint_color = 'black'
button.corner_radius = 5
button.title = ''
db = hb
o = ObjCClass('UIImage').systemImageNamed_(pad_elem['sf'])
with ui.ImageContext(db,db) as ctx:
#o.drawAtPoint_(CGPoint(0,0))
o.drawInRect_(CGRect(CGPoint(0, 0), CGSize(db,db)))
button.image = ctx.get_image()
button.data = pad_elem['data']
button.action = self.key_pressed
retain_global(button) # see https://forum.omz-software.com/topic/4653/button-action-not-called-when-view-is-added-to-native-view
self.add_subview(button)
def key_pressed(self, sender):
global mv
#import ui
#from objc_util import ObjCClass
tv = sender.objc_instance.firstResponder() # associated TextView
row = self.row
mv.textview_should_change(None, [row,row], sender.data)
#tv.insertText_(sender.data)
def OMColorPickerViewController(title=None, rgb=None):
v = ui.View()
if title:
v.name = title
v.rgb = None
vc = ObjCInstance(v)
colorpicker = ObjCClass('OMColorPickerViewController').new().autorelease()
clview = colorpicker.view()
v.frame = (0,0,512,960)
vc.addSubview_(clview)
done_button = ui.ButtonItem(title='ok')
def tapped(sender):
cl = colorpicker.color()
v.rgb = (cl.red(),cl.green(),cl.blue())
v.close()
done_button.action = tapped
v.right_button_items = [done_button]
if rgb:
color = ObjCClass('UIColor').colorWithRed_green_blue_alpha_(rgb[0], rgb[1], rgb[2], 1.0)
colorpicker.setColor_(color)
v.rgb = rgb
v.present('sheet')
v.wait_modal()
return v.rgb
@on_main_thread
def tableView_heightForRowAtIndexPath_(_self,_sel,tv,path):
try:
import sys, objc_util, ctypes
# For some reason, tv returns a NSNumber. But, our tableview is in _self
tv_o=objc_util.ObjCInstance(_self)
# get row and section from the path
indexPath=objc_util.ObjCInstance(path)
row=indexPath.row()
section=indexPath.section()
# get the pyObject. get as an opaque pointer, then cast to py_object and deref
pyo=tv_o.pyObject(restype=ctypes.c_void_p,argtypes=[])
tv_py=ctypes.cast(pyo.value,ctypes.py_object).value
# if the delegate has the right method, call it
if tv_py.delegate and hasattr(tv_py.delegate,'tableview_height_for_section_row'):
return tv_py.delegate.tableview_height_for_section_row(tv_py,section,row)
else:
return tv_py.row_height
except Exception as e:
import traceback
traceback.print_exc()
return 44
# set up the swizzle.. only needs to be done once
def setup_tableview_swizzle(override=False):
t=ui.TableView()
t_o=ObjCInstance(t)
encoding=ObjCInstanceMethod(t_o,'rowHeight').encoding[0:1]+b'@:@@'
if hasattr(t_o,'tableView_heightForRowAtIndexPath_') and not override:
return
swizzle.swizzle(ObjCClass(t_o._get_objc_classname()),
('tableView:heightForRowAtIndexPath:'),
tableView_heightForRowAtIndexPath_,encoding)
if not appex.is_running_extension():
#upon import, swizzle the textview class. this only ever needs to be done once
setup_tableview_swizzle(1)
class Outliner(ui.View):
def __init__(self, *args, **kwargs):
ui.View.__init__(self, *args, **kwargs)
ws,hs = ui.get_screen_size()
self.width, self.height = ws,hs
#self.frame = (0,0,375,667) # iPhone SE
self.name = 'Outliner'
self.background_color = 'white'
self.tv = ui.TableView(name='outliner')
#self.tv.border_width = 2
#self.tv.border_color = 'red'
self.tv.allows_selection = False
self.tv.data_source = ui.ListDataSource(items=[])
self.tv.data_source.delete_enabled = False
self.tv.separator_color=(1,0,0,0)
self.tv.delegate = self
self.tv.data_source.tableview_cell_for_row = self.tableview_cell_for_row
self.tv.data_source.tableview_number_of_rows = self.tableview_number_of_rows
self.tv.data_source.tableview_height_for_section_row = self.tableview_height_for_section_row
self.tv.background_color = (1,1,1)
#self.tv.border_width = 1
#d = 20*2
ht = 70
self.tv.frame = (0,ht,ws-2,hs-ht)
self.tv.delegate = self
#======== to be moved for textfikd in cell for row
#self.tv.font = ('Menlo',14)
self.tvo = ObjCInstance(self.tv)
#print(dir(self.tvo))
self.tv.row_height = -1
self.tvo.estimatedRowHeight = 44
self.add_subview(self.tv)
self.content = []
nb = 12
w = ui.get_screen_size()[0]
dd = 4
wb = (w - (nb+1)*dd)/nb
if wb > 32:
wb = 32
dd = (w - wb*nb)/(nb+1)
d = int(w/nb)
y = 30 + (ht - 30 - wb)/2
title = ui.Label(name='title')
title.frame = (0,10,self.width,30)
title.font = ('Menlo',16)
title.alignment = ui.ALIGN_CENTER
self.add_subview(title)
x = dd
b_close = ui.Button()
b_close.frame = (x,y,wb,wb)
b_close.image = ui.Image.named('iob:close_round_32')
b_close.action = self.close_action
self.add_subview(b_close)
x = x + wb + dd
b_version = ui.Button()
b_version.frame = (x,y,wb,wb)
w12 = ui.measure_string(Version+'_',font=('Menlo',12))[0]
fs = 12 * wb/w12
b_version.font = ('Menlo',fs)
b_version.title = Version
b_version.tint_color = 'green'
b_version.action = self.button_version_action
self.add_subview(b_version)
x = x + wb + dd
b_files = ui.Button()
b_files.frame = (x,y,wb,wb)
b_files.image = ui.Image.named('iob:ios7_folder_outline_32')
b_files.tint_color = 'blue'
b_files.action = self.button_files_action
self.add_subview(b_files)
x = x + wb + dd
b_settings = ui.Button()
b_settings.frame = (x,y,wb,wb)
b_settings.image = ui.Image.named('iob:ios7_gear_outline_32')
b_settings.action = self.button_settings_action
self.add_subview(b_settings)
x = self.width - wb - dd
b_format = ui.Button()
b_format.frame = (x,y,wb,wb)
o = ObjCClass('UIImage').systemImageNamed_('list.number')
with ui.ImageContext(32,32) as ctx:
o.drawAtPoint_(CGPoint(4,4))
b_format.image = ctx.get_image()
b_format.action = self.button_format_action
self.add_subview(b_format)
self.outline_format = 'decimal'
x = x - wb - dd
b_color = ui.Button()
b_color.frame = (x,y,wb,wb)
b_color.image = ui.Image.named('emj:Artist_Palette').with_rendering_mode(ui.RENDERING_MODE_ORIGINAL)
b_color.action = self.button_color_action
self.add_subview(b_color)
self.outline_rgb = (1,0,0)
self.outline_color = UIColor.colorWithRed_green_blue_alpha_(self.outline_rgb[0], self.outline_rgb[1], self.outline_rgb[2], 1)
x = x - wb - dd
b_font = ui.Button()
b_font.frame = (x,y,wb,wb)
with ui.ImageContext(32,32) as ctx:
ui.draw_string('A', rect=(16,9,16,16), font=('Academy Engraved LET',24))
b_font.image = ctx.get_image()
b_font.action = self.button_font_action
self.add_subview(b_font)
x = x - wb - dd
b_fsize = ui.Button()
b_fsize.frame = (x,y,wb,wb)
#b_fsize.title = 'font_size'
with ui.ImageContext(32,32) as ctx:
ui.draw_string('A', rect=(8,12,12,12), font=('Menlo',12))
ui.draw_string('A', rect=(16,9,16,16), font=('Menlo',16))
b_fsize.image = ctx.get_image()
b_fsize.action = self.button_fsize_action
self.add_subview(b_fsize)
x = x - wb - dd
b_search = ui.Button()
b_search.frame = (x,y,wb,wb)
b_search.image = ui.Image.named('iob:ios7_search_32')
b_search.action = self.button_search_action
self.add_subview(b_search)
x = x - wb - dd
b_undo = ui.Button(name='undo_button')
b_undo.frame = (x,y,wb,wb)
b_undo.action = self.button_undo_action
b_undo.enabled = False
self.add_subview(b_undo)
x = x - wb - dd
b_show = ui.Button()
b_show.frame = (x,y,wb,wb)
b_show.action = self.button_show_action
b_show.image = ui.Image.named('iob:ios7_eye_outline_32')
self.add_subview(b_show)
x = x - wb - dd
b_filter = ui.Button()
b_filter.frame = (x,y,wb,wb)
b_filter.action = self.button_filter_action
b_filter.image = ui.Image.named('iob:levels_32')
self.add_subview(b_filter)
sep = ui.Label()
sep.frame = (0,y+wb,self.width,1)
sep.background_color = 'lightgray'
self.add_subview(sep)
self.button_undo_enable(False,'')
self.font = 'Menlo'
self.font_size = 18
self.font_hidden = 6
font = UIFont.fontWithName_size_('Menlo', self.font_size)
font_hidden = UIFont.fontWithName_size_('Menlo', self.font_hidden)
self.text_color = UIColor.colorWithRed_green_blue_alpha_(0, 0, 1, 1)
self.text_attributes = {NSForegroundColorAttributeName:self.text_color, NSFontAttributeName:font}
self.text_attributes_hidden = {NSForegroundColorAttributeName:self.text_color, NSFontAttributeName:font_hidden}
self.outline_attributes = {NSForegroundColorAttributeName:self.outline_color, NSFontAttributeName:font}
self.outline_attributes_hidden = {NSForegroundColorAttributeName:self.outline_color, NSFontAttributeName:font_hidden}
self.link_color = UIColor.colorWithRed_green_blue_alpha_(0, 1, 1, 1)
self.modif = False
self.file = None
self.log = 'no'
self.filter = ('>',0)
self.device_model = str(ObjCClass('UIDevice').currentDevice().model())
#self.device_model = 'iPhone' # force for tests
path = sys.argv[0]
i = path.rfind('.')
self.prm_file = path[:i] + '.prm'
if os.path.exists(self.prm_file):
with open(self.prm_file, mode='rt') as fil:
x = fil.read()
self.prms = ast.literal_eval(x)
else:
self.prms = {}
self.prms['font'] = self.font
self.prms['font_hidden'] = self.font_hidden
self.log_file = path[:i] + '.log'
if 'popup menu orientation' not in self.prms:
self.prms['popup menu orientation'] = 'horizontal'
self.popup_menu_orientation = self.prms['popup menu orientation']
if self.device_model != 'iPad':
self.popup_menu_orientation = 'vertical'
if 'show original area' not in self.prms:
self.prms['show original area'] = 'no'
self.show_original_area = self.prms['show original area']
if 'show lines separator' not in self.prms:
self.prms['show lines separator'] = 'yes'
self.show_lines_separator = self.prms['show lines separator']
if 'checkboxes' not in self.prms:
self.prms['checkboxes'] = 'yes'
self.checkboxes = self.prms['checkboxes']
if 'delete option in red' not in self.prms:
self.prms['delete option in red'] = 'yes'
self.red_delete = self.prms['delete option in red']
if 'tap for popup' not in self.prms:
self.prms['tap for popup'] = 'single'
self.tap_for_popup = self.prms['tap for popup']
if 'autocapitalize type' not in self.prms:
self.prms['autocapitalize type'] = 'none'
self.autocapitalize_type = self.prms['autocapitalize type']
# temporary protection vs invalid data in .prm
if 'delete in red' in self.prms:
del self.prms['delete in red']
if 'auto_save' in self.prms:
del self.prms['auto_save']
if 'auto-save' not in self.prms:
self.prms['auto-save'] = 'no'
else:
# temporary protection vs invalid data in .prm
if 'auto-save' in self.prms['auto-save']:
self.prms['auto-save'] = 'no'
self.auto_save = self.prms['auto-save']
if 'folder' not in self.prms:
self.prms['folder'] = 'local'
self.folder = self.prms['folder']
local_path = sys.argv[0]
#print(local_path)
# /private/var/mobile/Containers/Shared/AppGroup/device-id/Pythonista3/Documents/
i = len('/private/var/mobile/Containers/Shared/AppGroup/')
j = local_path.find('/',i)
# on my ipad does not have same device_id as local Pythonista....
device_id_local = local_path[i:j]
#print(local_path,device_id_local)
if 'on_my_path' in self.prms:
path_on_my = self.prms['on_my_path']
else:
path_on_my = '?'
self.folders = {'local':'/var/mobile/Containers/Shared/AppGroup/'+device_id_local+'/Pythonista3/', 'iCloud':'/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/', 'on my\n' + self.device_model:path_on_my, 'iCloud\nDrive':'/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/'}
self.outline_formats = {
'decimal':(['v.0','v.v','v.v.v','v.v.v.v','v.v.v.v.v','v.v.v.v.v.v', 'v.v.v.v.v.v.v', 'v.v.v.v.v.v.v.v'],2),
'alphanumeric':(['I.', 'A.', 'i.', 'a.', '(1).', '(a).'],3),
'traditional':(['1.', 'A.', 'i.', 'a.', '(1).', '(a).', '((1)).', '((a)).'],3),
'bullets':(['•', '‣', '◦', '⦿', '⁃', '⦾', '◘'],3)
}
self.checkmark_ui_image = ui.Image.named('emj:Checkmark_3').with_rendering_mode(ui.RENDERING_MODE_ORIGINAL)
self.save_duration = None
self.orig_area = None
self.keyboard_y = 0
self.cells = {}
# must be last process of init
local_path = sys.argv[0]
if len(sys.argv) > 1:
# parameter passed
parm = sys.argv[1]
if parm.startswith('.'):
# extension passed
ext = parm
path = local_path
i = path.rfind('/')
path = path[:i+1]
f = File_Picker.file_picker_dialog('Pick a text file', root_dir=path, file_pattern=r'^.*\{}$'.format(ext))
if not f:
console.alert('❌ No file has been picked','','ok', hide_cancel_button=True)
return
print(f)
i = f.rfind('/')
path = f[:i+1]
file = f[i+1:]
self.prms['path'] = path
self.prms['file'] = file
else:
# file passed
path = local_path
i = path.rfind('/')
path = path[:i+1]
file = parm
if not os.path.exists(path+file):
console.alert('❌ '+file+' passed as argument',"does not exits",'ok', hide_cancel_button=True)
else:
i = file.rfind('.')
if i < 0:
i = len(file)
file_content = file[:i] + '.content'
if not os.path.exists(path+file_content):
console.alert('❌ '+file_content+' passed as argument',"does not exits",'ok', hide_cancel_button=True)
else:
self.prms['path'] = path
self.prms['file'] = file
if 'file' in self.prms:
# simulate files button and open last file
if not os.path.exists(self.prms['path']+self.prms['file']):
#console.hud_alert(self.prms['file']+' in .prm does not exist\nprm will be cleaned','error',1)
del self.prms['path']
del self.prms['file']
else:
self.button_files_action('Open')
def tableview_height_for_section_row(self,tv,section,row):
#print('tableview_height_for_section_row')
if tv.name != 'outliner':
return tv.row_height
vals,n,opts = tv.data_source.items[row]['content']
ft = (self.font, self.font_size)
if 'hidden' in opts:
if opts['hidden']:
ft = (self.font,self.font_hidden)
# build not showed TextField to compute its height with size_to_fit
stv = ui.TextView()
stv.width = tv.width
stv.font = ft
self.set_content_inset((stv))
stv.text = tv.data_source.items[row]['title']
stv.size_to_fit()
h = stv.height
del stv
return h
'''
undo = tv before action
action
undo:
redo = tv after action
tv = undo
redo:
tv = redo
'''
def button_undo_action(self,sender):
if sender.title.startswith('un'):