forked from inclement/noGo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·1232 lines (1084 loc) · 47.5 KB
/
main.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
#!/usr/bin/env python2
# Copyright 2013 Alexander Taylor
# This file is part of noGo.
# noGo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# noGo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with noGo. If not, see http://www.gnu.org/licenses/gpl-3.0.txt
# print 'DEBUG STUFF'
# import os
# print 'THIS DIR'
# print os.listdir('.')
from kivy.app import App
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle, Ellipse
from kivy.metrics import dp
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.stencilview import StencilView
from kivy.uix.dropdown import DropDown
from kivy.uix.scatter import Scatter
from kivy.uix.spinner import Spinner, SpinnerOption
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.screenmanager import *
from kivy.uix.settings import Settings, SettingsWithSpinner, SettingsWithTabbedPanel, SettingsWithNoMenu
from kivy.uix.settings import Settings
from kivy.adapters.listadapter import ListAdapter
#from kivy.uix.listview import ListView, ListItemButton
from mylistview import ListView, ListItemButton
from kivy.utils import platform
from kivy.animation import Animation
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty, ListProperty, AliasProperty, StringProperty, DictProperty, BooleanProperty, StringProperty, OptionProperty
from kivy.vector import Vector
from kivy.clock import Clock
#from navigationdrawer import NavigationDrawer
from kivy.core.audio import SoundLoader
from random import random as r
from random import choice
from math import sin
from functools import partial
from glob import glob
from os.path import abspath, exists
from os import mkdir, rename, environ, getenv, putenv
from shutil import copyfile
from json import dump as jsondump, load as jsonload, dump as jsondump
import json
from time import asctime, time, sleep
from gomill import sgf, boards
from abstractboard import *
from boardview import GuiBoard, BoardContainer, PhoneBoardView, TabletBoardView, GuessPopup, SaveQuery, MySpinnerOption, ReversibleSpinner
from boardwidgets import Stone, TextMarker, TriangleMarker, SquareMarker, CircleMarker, CrossMarker, VarStone
from miscwidgets import VDividerLine, DividerLine, WhiteStoneImage, BlackStoneImage, CarouselRightArrow, CarouselLeftArrow, AndroidTextInput
from info import InfoPage
from homepage import TabletHomeScreen, HomeScreen, OpenSgfDialog
from sgfcollections import DeleteCollectionQuestion, CollectionNameChooser, StandaloneGameChooser, GameChooserInfo, get_collectioninfo_from_dir, OpenChooserButton, CollectionsIndex, CollectionChooserButton, GameChooserButton, DeleteSgfQuestion, CollectionsList, Collection, CollectionSgf, get_collectioninfo_from_collection
from widgetcache import WidgetCache
if platform() == 'android':
from jnius import autoclass
import sys
# Config.set('graphics', 'width', '400')
# Config.set('graphics', 'height', '600')
# Keybindings
advancekeys = ['right','l']
retreatkeys = ['left','h']
nextvariationkeys = ['up','k']
prevvariationkeys = ['down','j']
trianglecodes = ['triangle','TR']
squarecodes = ['square','SQ']
circlecodes = ['circle','CR']
crosscodes = ['cross','MA']
textcodes = ['text','LB']
class NogoButton(Button):
pass
class CollectionProgress(Popup):
length = NumericProperty(1)
progress = NumericProperty(0)
def set_length(self,thing,value):
print 'thing is',thing
print 'val is',value
self.length = value
def set_progress(self, thing, value):
print 'prog thing is',thing
print 'prog val is', value
self.progress = value
def boardname_to_filepath(name):
if name == 'full board photo':
return './media/boards/edphoto_full_small2.png'
elif name == 'white':
return './media/white_pixel.png'
elif name == 'board section photo 1':
return './media/boards/edphoto_section.png'
elif name == 'lightened board photo 1':
return './media/boards/edphoto_section_light.png'
elif name == 'board section photo 2':
return './media/boards/edphoto_section_2.png'
elif name == 'plain dark':
return './media/boards/plain_light.png'
else:
return './media/boards/none.png'
def markercode_to_marker(markercode):
if markercode in trianglecodes:
return 'triangle'
elif markercode in squarecodes:
return 'square'
elif markercode in circlecodes:
return 'circle'
elif markercode in crosscodes:
return 'cross'
elif markercode in textcodes:
return 'text'
return None
def set_board_height(boardcontainer):
# Should be redundant now.
width = Window.width
height = Window.height
print 'window height,width',height,width
if height > width:
boardheight = width
boardcontainer.height = boardheight
boardcontainer.size_hint_y = None
print 'boardcontainer size',boardcontainer.size,boardcontainer.size_hint
def get_game_chooser_info_from_boardname(sm,boardname):
board = sm.get_screen(boardname).children[0].board
gameinfo = board.collectionsgf.info_for_button()
if 'wname' in gameinfo:
wname = gameinfo['wname']
else:
wname = 'Unknown'
if 'bname' in gameinfo:
bname = gameinfo['bname']
else:
bname = 'Unknown'
if 'filepath' in gameinfo:
filepath = gameinfo['filepath']
else:
filepath = 'Not yet saved'
if 'date' in gameinfo:
date = gameinfo['date']
else:
date = '---'
return {'boardname': boardname, 'wname': wname, 'bname': bname, 'filepath': filepath, 'date': date}
def get_temp_filepath():
tempdir = './games/unsaved'
return tempdir + '/' + asctime().replace(' ','_') + '.sgf'
class BoardSizeButton(ToggleButton):
gridsize = NumericProperty(19)
def current_selected_size(self):
ws = self.get_widgets('sizebuttons')
for entry in ws:
if entry.state == 'down':
return entry.gridsize
return 19
class NewBoardQuery(BoxLayout):
collections_list = ObjectProperty(None,allownone=True)
manager = ObjectProperty(None,allownone=True)
class BoardSizeButton(ToggleButton):
gridsize = NumericProperty(19)
def current_selected_size(self):
ws = self.get_widgets('sizebuttons')
for entry in ws:
if entry.state == 'down':
return entry.gridsize
return 19
class NewBoardQuery(BoxLayout):
collections_list = ObjectProperty(None,allownone=True)
manager = ObjectProperty(None,allownone=True)
class GameOptions(DropDown):
board = ObjectProperty(None,allownone=True)
class GameOptionsButton(Button):
ddn = ObjectProperty(None,allownone=True)
board = ObjectProperty(None,allownone=True)
def __init__(self,*args,**kwargs):
super(GameOptionsButton,self).__init__()
self.ddn = GameOptions(board=self.board)
def on_touch_up(self,touch):
self.ddn.board = self.board
if touch.grab_current == self:
self.ddn.open(self)
return super(GameOptionsButton,self).on_touch_up(touch)
class NextButton(Button):
board = ObjectProperty(None,allownone=True)
def on_touch_down(self, touch):
super(NextButton,self).on_touch_down(touch)
if self.collide_point(*touch.pos):
if self.board is not None:
self.board.stop_autoplay()
callback = self.board.start_autoplay
Clock.schedule_once(callback,1.1)
touch.ud['event'] = callback
def on_touch_up(self,touch):
super(NextButton,self).on_touch_up(touch)
try:
Clock.unschedule(touch.ud['event'])
except KeyError:
pass
class PrevButton(Button):
pass
starposs = {19:[(3,3),(3,9),(3,15),(9,3),(9,9),(9,15),(15,3),(15,9),(15,15)],
13:[(3,3),(3,9),(9,3),(9,9),(6,6)],
9:[(2,2),(6,2),(2,6),(6,6),(4,4)]}
class NogoManager(ScreenManager):
app = ObjectProperty(None,allownone=True)
boards = ListProperty([])
back_screen_name = StringProperty('')
# Settings properties to keep an eye on
touchoffset = ListProperty([0,0])
coordinates = BooleanProperty(False)
display_markers = BooleanProperty(True)
boardtype = StringProperty('./media/boards/none.png')
view_mode = StringProperty('phone')
collectionindex_to_refresh = BooleanProperty(False)
homescreen_to_refresh = BooleanProperty(False)
collections_to_refresh = ListProperty([])
def open_from_intentpath(self,path):
print 'asked to open_from_intentpath',path
names = self.screen_names
for name in names:
if name[:5] == 'Board':
board = self.get_screen(name)
try:
if board.children[0].board.collectionsgf.filen == path:
print 'filen is correct, name is',name
self.switch_and_set_back(name)
return
except IndexError:
print 'Tried to go to board that doesn\'t exist, maybe didn\'t load properly'
print 'path not already open, opening'
self.new_board(from_file=path,mode='Navigate')
def on_current(self,*args,**kwargs):
super(NogoManager,self).on_current(*args,**kwargs)
if self.current == 'Home' and self.homescreen_to_refresh:
self.refresh_open_games()
self.homescreen_to_refresh = False
if self.current == 'Collections Index' and self.collectionindex_to_refresh:
self.refresh_collections_index()
self.collectionindex_to_refresh = False
def add_collection_refresh_reminder(self, collection):
print 'Asked to remind collection refresh',collection
if collection not in self.collections_to_refresh:
self.collections_to_refresh.append(collection)
def switch_and_set_back(self,newcurrent):
print 'Asked to switch and set back',self.transition.is_active
print newcurrent, self.has_screen(newcurrent)
if newcurrent[:5] == 'Board' and self.has_screen(newcurrent):
print 'got to make_match bit'
self.make_board_match_view_mode(newcurrent)
elif newcurrent == 'Collections Index':
if not self.has_screen('Collections Index'):
self.create_collections_index()
if not self.transition.is_active:
self.back_screen_name = self.current
self.current = newcurrent
print 'Finished switching', self.back_screen_name, self.current
def go_home(self, fromright=False):
print 'going home'
if not self.transition.is_active:
if not fromright:
self.transition = SlideTransition(direction='right')
self.current = 'Home'
self.back_screen_name = 'Home'
self.transition = SlideTransition(direction='left')
def handle_android_back(self):
if platform() == 'android':
import android
res = android.hide_keyboard()
print 'HANDLING android back...'
self.go_back()
def go_back(self):
app = App.get_running_app()
# if app.navdrawer.state == 'open':
# return app.navdrawer.toggle_state()
print 'going back', self.back_screen_name
if not self.transition.is_active:
self.transition = SlideTransition(direction='right')
if self.current == self.back_screen_name or self.current[:5] == 'Board':
self.back_screen_name = 'Home'
print '->',self.back_screen_name
if self.back_screen_name in self.screen_names:
print 'going to',self.back_screen_name
self.current = self.back_screen_name
else:
self.current = 'Home'
self.transition = SlideTransition(direction='left')
def set_current_from_opengameslist(self,l):
print 'open games list is',l
if len(l)>0:
screenname = l[0].boardname
self.switch_and_set_back(screenname)
# self.back_screen_name = self.current
# self.current = screenname
def open_help(self):
if self.has_screen('Info Page'):
self.switch_and_set_back('Info Page')
else:
fileh = open('README.rst','r')
readme = fileh.read()
fileh.close()
infoscreen = Screen(name='Info Page')
infoscreen.add_widget(InfoPage(infotext=readme))
self.add_widget(infoscreen)
self.switch_and_set_back('Info Page')
def view_or_open_collection(self,selection,goto=True):
print 'asked to view_or_open',selection
if len(selection) == 0:
return False
collection_name = selection[0].colname
if self.has_screen('Collection ' + collection_name):
print 'screen already exists',collection_name
print 'supposed to refresh',self.collections_to_refresh
matching_refresh = filter(lambda j: j.name == collection_name,self.collections_to_refresh)
if len(matching_refresh) > 0:
self.refresh_collection(matching_refresh[0])
self.collections_to_refresh.remove(matching_refresh[0])
self.current = 'Collection ' + collection_name
else:
collections = App.get_running_app().collections
matching_collections = filter(lambda j: j.name == collection_name,collections.collections)
if len(matching_collections) > 0:
collection = matching_collections[0]
collection.finish_lazy_loading()
print 'Established opening',collection
screenname = 'Collection ' + collection.name
games = collection.games
args_converter = lambda k,j: j.info_for_button()
#print 'made args converter',games
if len(games)>0:
print args_converter('yay',games[0])
list_adapter = ListAdapter(data=games,
args_converter = args_converter,
selection_mode = 'single',
allow_empty_selection=True,
cls=GameChooserButton,
)
gc = StandaloneGameChooser(managedby=self,collection=collection)
gc.gameslist.adapter = list_adapter
print 'made gc and set adapter'
#print 'games are',games
#print 'gameinfos are', map(lambda j: j.gameinfo,games)
s = Screen(name=screenname)
s.add_widget(gc)
self.add_widget(s)
if goto:
self.switch_and_set_back(s.name)
def refresh_open_games(self):
homepage = self.get_screen('Home')
args_converter = lambda c,j: get_game_chooser_info_from_boardname(self,j)
list_adapter = ListAdapter(data=self.boards,
args_converter=args_converter,
selection_mode='single',
allow_empty_selection=True,
cls=OpenChooserButton,
)
homepage.children[0].opengames.adapter = list_adapter
def refresh_collection(self,collection):
print 'Asked to refresh collection',collection,collection.name
matching_screens = filter(lambda j: j == ('Collection ' + collection.name),self.screen_names)
if len(matching_screens) > 0:
scr = self.get_screen(matching_screens[0])
gc = scr.children[0]
games = collection.games
args_converter = lambda k,j: j.info_for_button()
#args_converter = testconverter
list_adapter = ListAdapter(data=games,
args_converter = args_converter,
selection_mode = 'single',
allow_empty_selection=True,
cls=GameChooserButton,
)
gc.gameslist.adapter = list_adapter
self.refresh_collections_index()
def open_sgf_dialog(self):
popup = Popup(content=OpenSgfDialog(manager=self),title='Open SGF',size_hint=(0.85,0.85))
popup.content.popup = popup
popup.open()
def board_from_gamechooser(self,selection):
if len(selection) > 0:
button = selection[0]
collection = button.collection
collectionsgf = button.collectionsgf
self.new_board(with_collectionsgf=collectionsgf,mode='Navigate')
def close_board_from_selection(self,sel):
print 'asked to close from sel',sel
if len(sel) > 0:
self.close_board(sel[0].boardname)
def close_board(self,name):
if self.has_screen(name):
pbvs = self.get_screen(name)
try:
pbvs.children[0].board.save_sgf()
except IndexError:
pass # Board not initialised
self.remove_widget(pbvs)
self.boards.remove(name)
print 'new boards',self.screens
def collection_tool_dialog(self):
'''Create and open a dialog popup for collection tools (import directory etc.)'''
App.get_running_app().build_collections_list()
pass
def new_board_dialog(self):
print 'Opening new_board_dialog'
App.get_running_app().build_collections_list()
dialog = NewBoardQuery(manager=self)
popup = Popup(content=dialog,title='Create new board...',size_hint=(0.85,0.9))
popup.content.popup = popup
collections_list = App.get_running_app().collections.collections
collections_args_converter = get_collectioninfo_from_collection
list_adapter = ListAdapter(data=collections_list,
args_converter=collections_args_converter,
selection_mode='single',
allow_empty_selection=True,
cls=CollectionChooserButton
)
dialog.collections_list.adapter = list_adapter
popup.open()
def new_board_from_selection(self,sel,gridsize=19,handicap=0):
if len(sel)>0:
collection = sel[0].collection
else:
collection = App.get_running_app().get_default_collection()
self.new_board(in_collection=collection,gridsize=gridsize,handicap=handicap)
def new_board(self,with_collectionsgf=None,in_collection=None,from_file='',mode='Play',gridsize=19,handicap=0,goto=True):
load_from_file = False
App.get_running_app().build_collections_list()
print '%% NEW BOARD'
print with_collectionsgf, in_collection, from_file
print type(from_file)
t1 = time()
# Get a collection and collectionsgf to contain and represent the board
filen = from_file
if with_collectionsgf is not None:
collectionsgf = with_collectionsgf
filen = collectionsgf.filen
collection = collectionsgf.collection
newboard = False
load_from_file = True
elif in_collection is not None:
collection = in_collection
collectionsgf = collection.add_game(can_change_name=True)
load_from_file = False
if from_file != '':
load_from_file = True
filen = from_file
collectionsgf.filen = filen
collectionsgf.can_change_name = False
else:
collection = App.get_running_app().get_default_collection()
collectionsgf = collection.add_game()
print 'Made new collectionsgf for the game',collectionsgf
load_from_file = False
if from_file != '':
load_from_file = True
filen = from_file
collectionsgf.filen = filen
collectionsgf.can_change_name = False
t2 = time()
print 't2 - t1 is...',t2-t1
if filen == '' and with_collectionsgf is None:
collectionsgf.filen = collectionsgf.get_default_filen() + '.sgf'
filen = collectionsgf.filen
load_from_file = False
t3 = time()
# Work out what screen name is free to put it in
i = 1
while True:
if not self.has_screen('Board %d' % i):
name = 'Board %d' % i
break
i += 1
s = Screen(name=name)
self.add_widget(s)
if goto:
self.current = name
t4 = time()
if self.view_mode == 'tablet':
pbv = TabletBoardView(collectionsgf=collectionsgf)
else:
pbv = PhoneBoardView(collectionsgf=collectionsgf)
pbv.board.collectionsgf = collectionsgf
# if platform() == 'android':
# #set_board_height(pbv.boardcontainer)
# pbv.boardcontainer.set_board_height()
gi = collectionsgf.gameinfo
if 'gridsize' in gi:
gridsize = gi['gridsize']
pbv.board.gridsize = gridsize
t5 = time()
if load_from_file:
print 'Trying to load from',filen
try:
pbv.board.load_sgf_from_file('',[filen])
except:
print 'Exception occurred, making popup'
popup = Popup(content=Label(text='Unable to open SGF. Please check the file exists and is a valid SGF.',title='Error opening file'),size_hint=(0.85,0.4),title='Error')
print 'popup made'
popup.open()
#self.close_board(name)
return False
else:
pbv.board.reset_gridsize(gridsize)
pbv.board.add_handicap_stones(handicap)
pbv.board.time_start()
s.add_widget(pbv)
pbv.screenname = name
pbv.managedby = self
pbv.spinner.text = mode
pbv.board.touchoffset = self.touchoffset
pbv.board.coordinates = self.coordinates
pbv.board.board_path = boardname_to_filepath(self.boardtype)
pbv.board.display_markers = self.display_markers
pbv.board.cache = App.get_running_app().cache
pbv.board.get_game_info()
pbv.board.save_sgf()
self.boards.append(name)
if self.view_mode == 'tablet':
pbv.board.comment_pre_text = 'This [b]tablet mode[/b] is currently experimental. It should work fine, but is still being tested and will be subject to change (more efficient layout etc.) and speed optimisation before being finalised.\n-----\n'
t6 = time()
print 'timings are'
print t6-t1, t6-t5, t5-t4, t4-t3, t3-t2, t2-t1
return pbv
def refresh_collections_index(self):
if 'Collections Index' not in self.screen_names:
self.create_collections_index()
return False
collections_index = self.get_screen('Collections Index').children[0]
collections_list = App.get_running_app().collections.collections
collections_args_converter = get_collectioninfo_from_collection
list_adapter = ListAdapter(data=collections_list,
args_converter = collections_args_converter,
selection_mode = 'single',
allow_empty_selection=True,
cls=CollectionChooserButton,
)
collections_index.collections_list.adapter = list_adapter
# def refresh_collection(self,dirn):
# sname = 'Collection ' + dirn
# if self.has_screen(sname):
# scr = self.get_screen(sname)
# self.remove_widget(scr)
# self.view_or_open_collection(dirn,goto=False)
def rebuild_homescreen(self,mode=None,goto=True):
if mode is None:
mode = self.view_mode
if 'Home' in self.screen_names:
oldhome = self.get_screen('Home')
self.remove_widget(oldhome)
if mode == 'tablet':
hs = TabletHomeScreen(managedby=self)
else:
hs = HomeScreen(managedby=self)
hs_screen = Screen(name='Home')
hs_screen.add_widget(hs)
self.add_widget(hs_screen)
self.refresh_open_games()
if goto:
if self.current == 'Home':
self.make_empty_screen()
self.current = 'emptyscreen'
self.current = 'Home'
def make_empty_screen(self):
if 'emptyscreen' not in self.screen_names:
self.add_widget(Screen(name='emptyscreen'))
def make_board_match_view_mode(self, name):
board = self.get_screen(name)
if self.view_mode == 'tablet':
if not isinstance(board.children[0], TabletBoardView):
print 'REFRESHING -> tbv'
board = self.get_screen(name)
self.close_board(name)
board = board.children[0]
board.board.save_sgf()
filen = board.board.collectionsgf.filen
reconstruction_path = board.board.get_reconstruction()
new_pbv = self.new_board(from_file=filen,mode='Navigate')
new_pbv.board.reconstruct_from(reconstruction_path)
new_pbv.board.comment_pre_text = 'This [b]tablet mode[/b] is currently experimental. It should work fine, but is still being tested and will be subject to change (more efficient layout etc.) and speed optimisation before being finalised.\n-----\n'
App.get_running_app().manager.refresh_open_games()
else:
if not isinstance(board.children[0], PhoneBoardView):
print 'REFRESHING -> pbv'
board = self.get_screen(name)
self.close_board(name)
board = board.children[0]
board.board.save_sgf()
filen = board.board.collectionsgf.filen
reconstruction_path = board.board.get_reconstruction()
new_pbv = self.new_board(from_file=filen,mode='Navigate')
new_pbv.board.reconstruct_from(reconstruction_path)
App.get_running_app().manager.refresh_open_games()
def create_collections_index(self):
app = App.get_running_app()
app.build_collections_list()
collections_list = App.get_running_app().collections.collections
collections_index = CollectionsIndex(managedby=self)
collections_args_converter = get_collectioninfo_from_collection
list_adapter = ListAdapter(data=collections_list,
args_converter = collections_args_converter,
selection_mode = 'single',
allow_empty_selection=True,
cls=CollectionChooserButton,
)
collections_index.collections_list.adapter = list_adapter
collections_screen = Screen(name='Collections Index')
collections_screen.add_widget(collections_index)
self.add_widget(collections_screen)
def propagate_input_mode(self,val):
if val == 'phone':
newtouchoffset = [0,3]
elif val == 'tablet/stylus':
newtouchoffset = [0,0]
else:
newtouchoffset = [0,3]
print 'An unrecognised input mode was chosen. Defaulting to [0,3] offset.'
self.touchoffset = newtouchoffset
for name in self.screen_names:
if name[:5] == 'Board':
curboard = self.get_screen(name)
curboard.children[0].board.touchoffset = newtouchoffset
def propagate_boardtype_mode(self,name):
self.boardtype = name
board_file = boardname_to_filepath(name)
print 'board file is',board_file
print 'propagating boardtype',name,board_file
for name in self.screen_names:
if name[:5] == 'Board':
curboard = self.get_screen(name)
curboard.children[0].board.board_path = board_file
def propagate_stonegraphics_mode(self):
for name in self.screen_names:
if name[:5] == 'Board':
curboard = self.get_screen(name)
curboard.children[0].board.replace_stones()
def propagate_markerdisplay_mode(self,val):
if val == 'False':
val = False
elif val == 'True':
val = True
else:
val = int(val)
self.display_markers = bool(val)
print 'propagating markerdisplay_mode',self.display_markers
for name in self.screen_names:
if name[:5] == 'Board':
curboard = self.get_screen(name)
curboard.children[0].board.display_markers = bool(val)
def propagate_coordinates_mode(self,val):
if val == 'False':
val = False
elif val == 'True':
val = True
else:
val = int(val)
self.coordinates = bool(val)
for name in self.screen_names:
if name[:5] == 'Board':
curboard = self.get_screen(name)
curboard.children[0].board.coordinates = bool(val)
def propagate_view_mode(self,val):
print 'PROPAGATING VIEW MODE',val
self.view_mode = val
if False: #platform() == 'android':
try:
if val == 'tablet':
App.get_running_app().try_android_rotate('landscape')
else:
App.get_running_app().try_android_rotate('portrait')
except AttributeError:
print 'VIEW MODE variables don\'t exist yet.'
elif platform() == 'android':
if val == 'phone':
Window.rotation = 0
elif val == 'tablet':
Window.rotation = 270
else:
Window.rotation = 0
self.rebuild_homescreen()
def query_delete_sgf(self,sel):
if len(sel)>0:
popup = Popup(content=DeleteSgfQuestion(manager=self,selection=sel),height=(140,'sp'),size_hint=(0.85,None),title='Are you sure?')
popup.content.popup = popup
popup.open()
def delete_sgf_from_selection(self,selection):
print 'Asked to delete from selection',selection
if len(selection)>0:
button = selection[0]
print 'collectionsgf is',button,button.collection,button.collectionsgf,button.filepath
self.delete_sgf(selection[0].collectionsgf)
def delete_sgf(self,collectionsgf):
collectionsgf.delete()
App.get_running_app().collections.save()
self.refresh_collection(collectionsgf.collection)
self.refresh_collections_index()
self.refresh_open_games()
def save_sgfs(self):
for name in self.screen_names:
if name[:6] == 'Board ':
s = self.get_screen(name)
s.children[0].board.save_sgf()
class DataItem(object):
def __init__(self, text='', is_selected=False):
self.text = text
self.is_selected = is_selected
def printargs(*args,**kwargs):
'###### printargs'
print args
print kwargs
'######'
# class NogoDrawer(NavigationDrawer):
# pass
class NavigationButtons(ScrollView):
manager = ObjectProperty(None, allownone=True)
navdrawer = ObjectProperty(None, allownone=True)
def on_touch_down(self, touch):
super(NavigationButtons, self).on_touch_down(touch)
if self.collide_point(*touch.pos):
print 'touched!'
print self.pos
print self.size
print self.parent, self.parent.children
print [child.pos for child in self.children]
print [child.size for child in self.children]
print [child.size for child in self.children[0].children]
class GobanApp(App):
version = StringProperty('0.4.0')
manager = ObjectProperty(None, allownone=True)
navdrawer = ObjectProperty(None, allownone=True)
cache = ObjectProperty(WidgetCache())
collections = ObjectProperty(None, allownone=True)
stone_type = StringProperty('default')
board_type = StringProperty('./media/boards/none.png')
sounds = BooleanProperty(True)
use_kivy_settings = True
settings_widget = SettingsWithNoMenu
title = 'noGo'
name = 'noGo'
prev_opened_file = StringProperty('')
def build(self):
print 'ENTERED BUILD()'
t1 = time()
# Load config
#print 'user data dir is', self.user_data_dir
config = self.config
#print 'my config is',config
sound = SoundLoader.load('./media/sounds/stone_sound5.mp3')
sound.volume = 0.05
self.stone_sound = sound
# Get any json collection backups if on android
if platform() == 'android':
if not exists('/sdcard/noGo'):
mkdir('/sdcard/noGo')
if not exists('/sdcard/noGo/collections'):
mkdir('/sdcard/noGo/collections')
if not exists('/sdcard/noGo/collections/unsaved'):
mkdir('/sdcard/noGo/collections/unsaved')
json_backups = glob('/sdcard/noGo/*.json')
for filen in json_backups:
with open(filen,'r') as fileh:
filestr = fileh.read()
if len(filestr) > 1:
name = filen.split('/')[-1]
copyfile(filen,'./collections/'+name)
# Load collections
# self.collections = CollectionsList().from_file()
#self.build_collections_list()
# Construct GUI
sm = NogoManager(transition=SlideTransition(direction='left'))
self.manager = sm
sm.app = self
# hv = Screen(name="Home")
# hs = HomeScreen(managedby=sm)
# hv.add_widget(hs)
# sm.add_widget(hv)
# sm.create_collections_index()
t2 = time()
print 'CONSTRUCTED manager and home',t2-t1
# Get initial settings from config panel
config = self.config
sm.propagate_input_mode(config.getdefault('Board','input_mode','phone'))
sm.propagate_coordinates_mode(config.getdefault('Board','coordinates','1'))
self.stone_type = config.getdefault('Board','stone_graphics','simple')
self.boardtype = config.getdefault('Board','board_graphics','simple')
sm.propagate_boardtype_mode(self.boardtype)
sm.propagate_view_mode(config.getdefault('Board','view_mode','phone'))
self.set_sounds(config.getdefault('Board','sounds','0'))
# Rebuild homescreen *after* setting phone/tablet mode
#sm.add_widget(Screen(name='emptyscreen'))
sm.rebuild_homescreen()
sm.current = 'Home'
self.bind(on_start=self.post_build_init)
if platform() == 'android':
from android import activity
activity.bind(on_new_intent=self.on_intent)
self.PythonActivity = autoclass('org.renpy.android.PythonActivity')
self.ActivityInfo = autoclass('android.content.pm.ActivityInfo')
t3 = time()
print 'RETURNING SM',t3-t2, t3-t1
#drawer = NogoDrawer()
#drawer.add_widget(NavigationButtons())
#drawer.add_widget(Image(source='media/logo_big2.png',
# allow_stretch=True,
# mipmap=True))
#drawer.add_widget(sm)
#self.navdrawer = drawer
#return drawer
return sm
def build_collections_list(self):
if self.collections is None:
self.collections = CollectionsList()
cl = self.collections
#progress = CollectionProgress()
#cl.popup = progress
#progress.open()
#sleep(1)
cl.from_file()
#progress.dismiss()
def try_android_rotate(self,dir='portrait'):
if dir == 'landscape':
self.PythonActivity.mActivity.setRequestedOrientation(self.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
else:
self.PythonActivity.mActivity.setRequestedOrientation(self.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
def on_intent(self,intent):
print 'INTENT'
print 'INTENT'
print 'INTENT'
print 'INTENT'
print 'INTENT'
print '!!!!!'
print 'on_intent called'
action = intent.getAction()
print 'action is',action
if action == 'android.intent.action.VIEW':
print 'Trying to act on intent'
#sleep(5)
print 'Slept briefly'
path = intent.getData().getPath()
print 'going for path',path
#self.manager.go_home()
Clock.schedule_once(lambda j: self.manager.open_from_intentpath(path),1.1)
#self.manager.open_from_intentpath(path)
# def on_resume(self,*args):
# print 'RESUMED'
# print 'RESUMED'
# print 'RESUMED'
# print 'RESUMED'
# print 'RESUMED'
def on_start(self,*args,**kwargs):
print '\nON_START',args,kwargs,'\n'
print 'environment',environ.get('PYTHON_OPENFILE')
open_file = getenv('PYTHON_OPENFILE','').replace('%20',' ')
print 'open_file is',open_file
if open_file != '':
putenv('PYTHON_OPENFILE','')
Clock.schedule_once(lambda j: self.manager.open_from_intentpath(open_file),1.1)
super(GobanApp,self).on_start(*args,**kwargs)
# def on_resume(self,*args,**kwargs):
# # print 'ON_RESUME',args,kwargs
# # print 'environment',environ.get('PYTHON_OPENFILE')
# # open_file = getenv('PYTHON_OPENFILE','').replace('%20',' ')
# # print 'open_file is',open_file
# # if open_file != '' and open_file != self.prev_opened_file:
# # self.prev_opened_file = open_file
# # self.manager.new_board(from_file=open_file,mode='Navigate')
# super(GobanApp,self).on_resume(*args,**kwargs)
def get_application_config(self):
if platform() == 'android':
dirn = self.user_data_dir + '/nogo.ini'