sequence.py 43.44 KiB
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
import os
import time
import uuid
import functools
import threading
import numpy as np

from kivy.lang import Builder
from kivy.utils import platform
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.gridlayout import GridLayout
from kivy.clock import Clock, mainthread
from kivy.graphics import Color, Rectangle
from kivy.properties import StringProperty, ObjectProperty, NumericProperty, ListProperty, BooleanProperty
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.scrollview import ScrollView
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.stencilview import StencilView

from kivymd.uix.button import MDRaisedButton, MDFlatButton, MDFloatingActionButton
from kivymd.uix.list import MDList, OneLineListItem, TwoLineListItem, ThreeLineListItem



# from kivymd.uix.tab import MDTabbedPanel, MDTab
from kivymd.uix.toolbar import MDToolbar
from kivymd.uix.textfield import MDTextField
from .mddialog import  MDDialog
from kivymd.uix.label import MDLabel
from .widgetsmd import MDNumberInput, yesno_box
from kivymd.uix.list import MDList
from ui.kivy.cam import CameraClick

from ui.kivy.widgets import apply_image
from ui.kivy import widgets

import kivy.garden.mapview
from kivy.garden.mapview import MapSource, MapMarker, MapMarkerPopup


from .widgetsmd import BDDialog
from . import chaining
from .i18n import i18nstr, I18NProperty as _, I18NContainerBehavior


class BoxStencil(BoxLayout, StencilView):
    """
    see https://kivy.org/doc/stable/api-kivy.uix.stencilview.html
    """
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            super().on_touch_down(touch)


if platform=='android':
    from jnius import autoclass

    PythonActivity = autoclass('org.kivy.android.PythonActivity')
    Intent = autoclass('android.content.Intent')
    String = autoclass('java.lang.String')

Builder.load_string("""
<SequenceCapture>:
    thumbs:thumbs
    # cam:cam
    orientation:'vertical'
    BoxLayout:
        orientation:'horizontal'
        size_hint:1,1
        BoxLayout:
            orientation:'vertical'
            size_hint:.1,1
            ThumbListView:
                id:thumbs
                size_hint:1,.9
            MDFloatingActionButton:
                id:btn_next
                icon:                'check'
                opposite_colors:    True
                elevation_normal:    8
                pos_hint:            {'center_x': 0.5, 'center_y': 0.2}
                # disabled: disable_the_buttons.active
                on_release:root.dispatch("on_capture_done")
        BoxLayout:
            id:cam_container
        # CameraClick:
        #     id:cam
        #     # config:root.project.config
        #     target_dir:root.sequence_path or '.'
        #     on_photo_shot:root.reload_thumbs()
    # MDRaisedButton:
    #     id:btn_next
    #     size_hint:1,None
    #     height:'48dp'
    #     text:'next'
    #     on_release:root.dispatch("on_capture_done")

""")


class SequenceCapture(BoxLayout):
    """
    capture a sequence of images
    """
    project = ObjectProperty(None)
    sequence = ObjectProperty(None)
    sequence_path = StringProperty(None)
    cam = ObjectProperty()

    def __init__(self, *a, **kw):
        super(SequenceCapture, self).__init__(*a, **kw)
        self.register_event_type("on_capture_done")

    def on_sequence(self, *a, **kw):
        print("SequenceCapture: sequence changed, self.project:", self.project)
        self.sequence_path = self.sequence.path
        self.thumbs.read_dir(self.sequence_path)
        self.ids.btn_next.text='next:'+self.sequence.relpath
        if self.cam:
            self.cam.target_dir = self.sequence_path

    def on_project(self, *a, **kw):
        print('SequenceCapture: project changed:', self.project)
        if self.cam:
            self.cam.config=self.project.config

    def reload_thumbs(self, *a):
        print('reload_thunbs')
        self.thumbs.read_dir(self.sequence_path, incremental=True)

    def init_cam(self):
        if not self.cam:
            # CameraClick:
            # id:cam
            # # config:root.project.config
            # target_dir:root.sequence_path or '.'
            # on_photo_shot:root.reload_thumbs()
            # import pdb;pdb.set_trace()
            camclick = CameraClick(id='cam', target_dir=self.sequence_path or '.')
            camclick.bind(on_photo_shot=self.reload_thumbs)
            self.ids.cam_container.add_widget(camclick)
            self.cam = camclick
            self.cam.config = self.project.config

    def on_capture_done(self):
        """dummy handler"""


Builder.load_string("""
<SequenceProps>:
    cols:1
    # row_default_height:40
    # row_force_default:True
    orientation:'vertical'
    padding: dp(48)
    spacing:10
    # height: 120  #self.minimum_height

    # Label:
    #     text:'name'
    # TextInput:
    #     id:name
    #     text:root.propose_name()
    BoxLayout:
        size_hint:1,None
        height:list.height
        MDList:
            id:list
            cols:1
            size_hint:1,None
            orientation:'vertical'
        
            MDTextField:
                id:name
                hint_text: "Poltername"
                helper_text: root.text_pile_name
                helper_text_mode: "persistent"
                text:root.propose_name()
                size_hint:1,None
                # height:'80sp'
                
            MDNumberInput:
                id:length
                helper_text:root.text_log_length
                helper_text_mode:'persistent'
                size_hint:1,None
                value:4
                textsize:15
                step:.5
                height:'60sp'
                
            MDTextField:
                id:service_provider
                hint_text:root.text_service_provider
                
            MDTextField:
                id:comment
                hint_text:root.text_comment
                
            MDLabeledCheckbox:
                id:overlapping
                text: root.text_overlapping 
                size_hint:1,None
                active:True
                height:'40sp'
    
            TwoLineListItem:
                id:sequence_id
                text: 'id'
                # secondary_text: 
        
            MDRaisedButton:
                text:root.text_next
                on_release:root.props_changed()
                
            TwoLineListItem:
                text: root.text_location
                secondary_text:str(root.location) if root.location else ''
""")


class SequenceProps(ScrollView):
    """"""
    data = ObjectProperty({})
    location = ObjectProperty()
    show_delete = BooleanProperty(False)

    text_next = _('next')
    text_location = _('location')
    text_overlapping = _('overlapping')
    text_comment = _('comment')
    text_service_provider = _('service provider')
    text_log_length = _('log length')
    text_pile_name = _('pile name')
    text_delete_pile = _('delete pile')

    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)
        self.register_event_type("on_props_changed")
        self.register_event_type("on_delete_selected")
        self.bind(data=self.on_data)
        Clock.schedule_once(self.after_init)

    def after_init(self, *a):
        delete_button=MDRaisedButton(text=self.text_delete_pile)
        delete_button.bind(
            on_release=lambda dt:
            self.dispatch("on_delete_selected"))

        if self.show_delete:
            self.ids.list.add_widget(delete_button)

    def on_data(self, *a):
        print('SequenceProps:on_data', self.data)
        self.ids.length.value=self.data.get('length', 4)
        self.ids.name.text=self.data.get('name', '')
        self.ids.service_provider.text=self.data.get('service_provider','')
        self.ids.sequence_id.secondary_text='<%s>' % self.data.get('id','')
        self.ids.comment.text = self.data.get('comment','')
        self.ids.overlapping.active = self.data.get('overlapping', True)

    def propose_name(self):
        return "neuer polter"

    def read_fields(self):
        self.data['length'] = self.ids.length.value
        self.data['name'] = self.ids.name.text
        self.data['service_provider'] = self.ids.service_provider.text
        self.data['comment'] = self.ids.comment.text
        self.data['overlapping'] = self.ids.overlapping.active

    def props_changed(self, *a):
        self.read_fields()
        self.dispatch("on_props_changed")

    def on_props_changed(self, *a, **kw):
        """dummy default handler"""

    def on_delete_selected(self, *a):
        """"""


Builder.load_string("""
<SequencesList>:
    orientation:'vertical'
    sequences_list:sequences_list
    
    ScrollView:
        size_hint:1,1
        MDList:
            id:sequences_list
            size_hint_y: None
            # height: self.minimum_size[1]
            cols: 1
    BoxLayout:
        size_hint:1,.2
        orientation:'horizontal'
        MDRaisedButton:
            text:'Neuen Polter anlegen'
            on_release: root.dispatch('on_new_sequence')
        MDFlatButton:
            text:'reload'
            on_release: root.load()
""")


class SequencesList(BoxLayout):
    """
    SequenceContainer
    """

    sequences = ObjectProperty()

    def __init__(self, *a, **kw):
        super(SequencesList, self).__init__(*a, **kw)
        self.register_event_type("on_new_sequence")
        self.register_event_type("on_sequence_selected")

    def on_sequences(self, *a):
        print('on_sequences')
        Clock.schedule_once(self.load, 0)

    def load(self, *a, **kw):
        """draws itself"""
        t=time.time()
        print('begin SequencesList::load')
        sequences = list(self.sequences.list_sequences(do_load=True))
        # sequences = filter(lambda x:x.has_location, sequences)

        sequences = sorted(sequences, key=lambda x:x.name, reverse=True)
        self.sequences_list.clear_widgets()
        for sequence in sequences:

            butt = OneLineListItem(text=sequence.name, size_hint_y=None, height=44)
            butt.sequence = sequence
            butt.bind(on_release=self.on_select)
            self.sequences_list.add_widget(butt)
            self.sequences_list.height += butt.height

        print('en SeuencesList::load:', time.time()-t)
    def on_new_sequence(self):
        """dummy handler"""

    def on_sequence_selected(self, sequence_name):
        """dummy handler"""

    def on_select(self, butt):
        print('sequeces_list:', butt.text)
        self.dispatch("on_sequence_selected", butt.text)


Builder.load_string("""
<SequenceMarkerPopup>:
    lat: 50.6394
    lon: 3.057
    popup_size: dp(230), dp(130)
    
    Bubble:
        BoxLayout:
            orientation: "vertical"
            padding: "5dp"

            on_touch_down:
                root.handle_touchdown(*args)
            Label:
                text: root.sequence.name
                markup: True
                halign: "center"
            Button:
                size_hint:1,.3
                text: 'open'
                on_release: root.dispatch("on_clicked")
""")


class SequenceMarkerPopup(MapMarkerPopup):
    """
    this content will be displayed on the map when clicking on a marker
    """
    sequence = ObjectProperty()

    def __init__(self, *a, **kw):
        # super(ButtonBehavior, self).__init__(*a, **kw)
        super(SequenceMarkerPopup, self).__init__(*a, **kw)
        self.register_event_type("on_clicked")

    def on_clicked(self, *a):
        """dummy handler"""

    def handle_touchdown(self, widget, event, **kw):
        print('touchdown')
        if not widget.collide_point(*event.pos):
            print('event outside widget')
            self.is_open=False


Builder.load_string("""
<SequencesMapView>:
    id:mapview
    mapview:mapview
    MapView:
        id: mapview
        zoom: 15
""")


class SequencesMapView(BoxLayout):
    """"""
    sequences = ObjectProperty()
    """thats the sequences container"""

    def __init__(self, sequences, *a, **kw):
        super(SequencesMapView, self).__init__( *a, **kw)
        self.sequences=sequences
        self.register_event_type("on_sequence_selected")

    def on_sequence_selected(self, *a):
        """dummy handler"""

    def on_sequences(self, *a):
        print('on_sequences')
        Clock.schedule_once(self.draw, 0)

    def on_marker_pressed(self, marker):
        print("marker pressed:", marker, marker.sequence)
        self.dispatch("on_sequence_selected", marker.sequence.name)

    def open_sequence(self, sequence, *a):
        self.dispatch("on_sequence_selected", sequence.name)

    def draw(self, *a):
        """draws itself"""
        # import pdb;pdb.set_trace()
        sequences = list(self.sequences.list_sequences(do_load=True))
        sequences = [x for x in sequences if x.has_location]
        sequences = sorted(sequences, key=lambda x:x.name, reverse=True)
        latest=sequences[:10]
        locs=[x.location for x in latest]

        # compute the medium location of recent N sequences
        medium_location=functools.reduce(lambda a,b: ((a[0]+b[0])/2,(a[1]+b[1])/2), locs)

        print('medium:', medium_location)

        self.mapview.center_on(*medium_location)

        for sequence in sequences:
            lat, int = sequence.location
            # print lat, long
            # marker=MapMarker(lon=long, lat=lat, on_press=self.on_marker_pressed)
            marker=SequenceMarkerPopup(lon=int, lat=lat, sequence=sequence)
            marker.bind(on_clicked=functools.partial(self.open_sequence, sequence))
            marker.sequence=sequence
            self.mapview.add_marker(marker)


Builder.load_string("""
<SequenceThumbView>:
    content:content
    orientation:'vertical'

    AsyncImage:
        id:content
        # source:root.source
""")


class SequenceThumbView(ButtonBehavior, BoxLayout):
    """
    Thumbnail view on an image file, does automatic
    resize to width
    """
    owner = ObjectProperty()
    source = StringProperty()
    fname = StringProperty()
    image = ObjectProperty()  # model.PositiveImage

    def __init__(self, image, *a, **kw):
        # super(SequenceThumbView, self).__init__(*a,**kw)  # damn, warum geht das nicht???

        ButtonBehavior.__init__(self, *a, **kw)
        self.register_event_type("on_img_click")

        self.image=image

    @property
    def path(self):
        return self.image.path

    def on_release(self, *a, **kw):
        self.dispatch("on_img_click", self.image)

    def on_img_click(self, source):
        """default handler for image selection"""
        # print 'img select default handler:', source

    def on_image(self, widget, image):
        """loads image from PositiveImage"""
        # self.source=source
        # width=self.width
        width=250
        # print 'on_source: width:', self.width
        if widget == self:
            # img = imread(source, True, width=width)

            apply_image(self.content, image.img)

            # print 'ThumbView::set_image : ', width


Builder.load_string("""
<SequenceThumbListView>:
    do_scroll_x:False
    GridLayout:
        id:content
        cols:1
        spacing:2
        size_hint:1,None

        # Label:
        #     text:'thumbs here'
""")


class SequenceThumbListView(ScrollView):
    """"""
    sequence = ObjectProperty()  # model.Sequence

    def __init__(self, *a, **kw):
        super(SequenceThumbListView, self).__init__(*a, **kw)
        self.register_event_type("on_image_select")

    def add_image(self, image):

        thumb = SequenceThumbView(image=image, owner=self, size_hint=(1, None))
        thumb.bind(on_img_click=self.on_img_click)
        self.ids.content.height += thumb.height
        self.ids.content.add_widget(thumb)

    @property
    def fnames(self):
        # import pdb;pdb.set_trace()
        return [t.path for t in self.ids.content.children]

    def read_sequence(self, sequence, reset=False, incremental=True):
        if reset:
            self.ids.content.clear_widgets()
            self.ids.content.height = 0

        for pimg in sequence:
            self.add_image(pimg)

    def reload(self, reset=True, incremental=True):
        self.read_sequence(self.sequence, reset=reset, incremental=incremental)

    def on_sequence(self, *a):
        self.read_sequence(self.sequence, True)

    def on_img_click(self, widget, image):
        # self.parent.ids.editor.source = source
        self.dispatch('on_image_select', image)

    def on_image_select(self, imgpath):
        """dummy impl"""

from kivymd.uix.bottomsheet import MDGridBottomSheet, MDBottomSheet

Builder.load_string("""
<SequenceImageInformation>:
    orientation:'vertical'

    MDList:
        TwoLineListItem:
            text:'image path'
            secondary_text:root.image.path if root.image else '--'
    
        TwoLineListItem:
            text:'shapes detected'
            secondary_text:str(root.image.count_detected_shapes)
    
        TwoLineListItem:
            text:'unique shapes'
            secondary_text:str(root.image.count_unique_shapes)
    
        TwoLineListItem:
            text:'area of shapes detected'
            secondary_text:str(root.image.area_detected_shapes)
    
        TwoLineListItem:
            text:'area unique'
            secondary_text:str(root.image.area_unique_shapes)

        TwoLineListItem:
            text:'distance'
            secondary_text:str(root.image.distance)
        
        TwoLineListItem:
            text:'camera FOV'
            secondary_text:str(root.image.camera_fov)
            
        TwoLineListItem:
            text:'resolution'
            secondary_text:str(root.image.img.shape)

        TwoLineListItem:
            text:'resolution undistorted'
            secondary_text:str(root.image.img_undistorted.shape)

        TwoLineListItem:
            text:'width'
            secondary_text:str(root.image.width)

        TwoLineListItem:
            text:'ref width'
            secondary_text:str(root.image.ref_width)
            
        TwoLineListItem:
            text:'location'
            secondary_text:str(root.image.location)

""")


class SequenceImageInformation(ScrollView):
    """"""
    image = ObjectProperty(None)

    def __init__(self, *a, **kw):
        super(SequenceImageInformation, self).__init__(*a, **kw)

from kivymd.uix.list import MDList
from kivy.uix.scrollview import ScrollView


Builder.load_string("""
<SequenceImageDetectionOptions>:
    cols:1
    size_hint:1,None
    orientation:'vertical'
    # MDList:
    
    DropDownList:
        # text:'stages-18'
        width: sp(160)
        text: root.cascade_name
        id: cascades_list
        values: root.cascade_names
        # values:[] # root.project.list_cascades() if root.project else []

    MDNumberInput:
        id:scale_factor
        height:sp(48)
        size_hint:None,None
        value: root.scale_factor
        step:.01
        minimum:1.01
        textsize:6
        hint_text:'scale factor'
    
    
    MDNumberInput:
        height:sp(48)
        datatype:int
        textsize:6
        hint_text:'min neighbors'
        id:min_neighbors
        size_hint:None,None
        value: root.min_neighbors
        step:1
        minimum:0

    MDLabeledCheckbox:
        id:smooth
        size_hint:1, None
        text:root.text_smooth
        active:root.smooth
    
""")

class SequenceImageDetectionOptions(BoxLayout):
    """"""
    scale_factor = NumericProperty()
    min_neighbors = NumericProperty()
    cascade_name = StringProperty('lbp-16-11')
    cascade_names = ListProperty([])
    smooth = BooleanProperty()

    text_smooth = _('smooth')


Builder.load_string("""
<SequenceImageView>:
    orientation:'vertical'
    image_widget:image
    # cascades_list:cascades_list
    # status: status
    RelativeLayout:
        size_hint:1,1
        BoxStencil:
            size_hint:1,1
            ScatterLayout:
                size_hint:1,1
                do_rotation:False
                AsyncImage:
                    id:image
""")


class SequenceImageView(BoxLayout, widgets.ImageClassifierMixin):
    """
    View class for displaying model.PositiveImage
    """
    image = ObjectProperty()
    predecessor = ObjectProperty()  # precious image in sequence
    successor = ObjectProperty()    # next image in sequence
    sequence = ObjectProperty()

    def on_image(self, *a):
        apply_image(self.image_widget, self.image.img_undistorted)
        # self.ids.info.text = "distance: %s, ref:%s" % \
        #                      (self.image.distance, self.image.ref_distance)
        self.clear_detections()
        self.update()
        # apply_image(self.image_widget, self.image.img)

    def on_sequence(self, *a):
        """"""
        # self.cascades_list.values = self.sequence.list_cascades()
        # import pdb;pdb.set_trace()

    def detect_shapes(self):
        print('detect_shapes:')
        cascade = self.sequence.load_cascade(self.cascades_list.text)
        self.image.detect_and_store_shapes(cascade,
                                           draw_markers=False,
                                           scale_factor=self.ids.scale_factor.value,
                                           min_neighbors=self.ids.min_neighbors.value)

        self.update()

    def draw_shapes(self, shapes, circle_color=(1,1,0), text_color=(1,0,0), autoclear=True):
        if autoclear:
            self.clear_detections()
        with self.image_widget.canvas.after:
            for (x, y, radius) in shapes:
                self.draw_circle(x, y, radius, color=circle_color)
                diameter = self.image.pixel2cm(radius*2)
                diameter_rounded = int(np.round(diameter))
                text = str(diameter_rounded)
                # text="%s - %s" % (diameter_rounded, radius * 2)
                self.draw_centered_text(x, y, text, color=text_color)

    def draw(self):
        if self.image.detected_shapes is not None:
            self.draw_shapes(self.image.detected_shapes, circle_color=(.7, .7, .7), text_color=(.7,.7,.7, 1))

        if self.image.unique_shapes is not None:
            self.draw_shapes(self.image.unique_shapes, circle_color=(1, 1, 0), text_color=(1, 0, 0), autoclear=False)

        # if self.image.shadow_shapes is not None:
        #     self.draw_shapes(self.image.shadow_shapes, circle_color=(.7,.7,.7), text_color=(0, 1, 0), autoclear=False)

    def update(self):
        self.draw()

    def show_info(self):
        if self.image:
            content = SequenceImageInformation(image=self.image)

            dialog = BDDialog(title="Information",
                              # content=content,
                              auto_dismiss=True,
                              size_hint=(1, 1)
                              )

            dialog.content = content
            dialog.add_action_button("Ok", lambda *x: dialog.dismiss())
            dialog.open()


Builder.load_string("""
<ProgressContent>:
    # height:200
    orientation:'vertical'
    log:log
    sublog:sublog
    details: details
    valign: 'middle'
    size_hint_y:None
    BoxLayout:
        # MDLabel:
        #     text:'Task'
        MDLabel:
            id:log
            text:root.text_detection_task
            theme_text_color: 'Primary'
    BoxLayout:
        MDLabel:
            id:sublog
            text:root.text_progress
            theme_text_color: 'Primary'

    MDLabel:
        id:details
        theme_text_color: 'Primary'
""")


class ProgressContent(BoxLayout):
    """"""
    # def __init__(self, *a, **kw):
    #     import pdb;pdb.set_trace()
    #     super(ProgressContent, self).__init__(self, *a, **kw)
    text_detection_task = _('detection task')
    text_progress = _('progress')

Builder.load_string("""
<SequenceView>:
    orientation:'horizontal'
    image_view:image_view
    thumbs:thumbs
    image_view:image_view
    status:status
    # substatus:substatus
    # progress:progress
    # anchor_x:'left'
    
    SequenceThumbListView:
        id:thumbs
        width:200
        size_hint:.25,1
        sequence:root.sequence
        on_image_select:root.on_image_select(*args)
    BoxLayout:
        orientation:'vertical'
        size_hint: 1,1
        SequenceImageView:
            id: image_view
            sequence: root.sequence
            size_hint: 1,.95
        BoxLayout:
            id:buttons
            size_hint:1, None
            height:root.ids.compute.height * 1.2
            valign:'middle'
            canvas:
                Color:
                    rgb: 1,1,1
                Rectangle:
                    pos:0,0
                    size:self.size    
                
            MDRaisedButton:
                id:compute
                text:'berechnen!'
                # on_release:root.detect_dedup()
                on_release:root.start_computation()
                
            MDIconButton:
                icon:'file-document'
                # text:'properties'
                on_release:root.show_props()
                
            MDIconButton:
                icon:'share-variant'
                on_release:root.on_share()
                
            MDIconButton:
                icon:'content-copy'
                on_release:root.on_capture_dependent_sequence()

            MDIconButton:
                icon:'information-outline'
                on_release:root.ids.image_view.show_info()
                
            BoxLayout:
                orientation:'vertical'
                MDLabel:
                    id: status
                    theme_text_color: 'Primary'
                    
                # MDLabel:
                #     id: substatus
                    
            MDIconButton:
                icon:'settings'
                on_release:root.options_dialog()
                    
""")


class SequenceView(BoxLayout):
    """"""
    project = ObjectProperty()
    path = StringProperty()
    project_path = StringProperty()
    sequence_path = StringProperty()
    sequence = ObjectProperty()
    progress_dialog = ObjectProperty(None, allownone=True)
    scale_factor = NumericProperty(1.08)
    min_neighbors = NumericProperty(3)
    cascade_name = StringProperty('lbp-16-11')
    smooth = BooleanProperty(False)

    text_properties = _('properties')
    text_options = _('options')
    text_shapes_detected = _('shapes detected')
    text_detecting = _('log detection')
    text_progress = _('progress')
    text_dedup = _('dedup')
    text_dedupped = _('dedupped')
    text_keypoints = _('keypoints')
    text_ready = _('ready')

    def __init__(self, *a, **kw):
        super(SequenceView, self).__init__(*a, **kw)
        Clock.schedule_once(self.after_init, 0)
        self.register_event_type('on_new_dependent_sequence')
        self.register_event_type('on_sequence_deleted')

    def on_new_dependent_sequence(self, *a):
        """dummy handler"""

    def on_sequence_deleted(self, *a):
        """"""

    def after_init(self, *a):
        app=App.get_running_app()
        if app.show_editor:
            editorbutton=MDRaisedButton(text='editor')
            editorbutton.bind(on_release=self.open_editor)
            self.ids.buttons.add_widget(editorbutton)

    def open_editor(self, *a):
        # import pdb;pdb.set_trace()
        wiz=self.parent.parent.parent
        wiz.switch_to_editor()

    def on_sequence(self, *a):
        # self.ids.lbl.text=self.sequence.path
        # import pdb;pdb.set_trace()
        print('on_sequence:', end=' ')
        print(self.sequence.path)
        # self.ids.sequence_images.path=self.sequence.path

    def on_image_select(self, widget, image):
        self.image_view.image=image

    def reload(self, **kw):
        self.thumbs.reload(*kw)
        if len(self.sequence) > 0:
            self.image_view.image = self.sequence[0]

    def detect_shapes(self, *a):
        cascade = self.sequence.load_cascade(self.cascade_name)
        self.sequence.detect_and_store_shapes(cascade,
            draw_markers=False,
            scale_factor=self.scale_factor,
            min_neighbors=self.imin_neighbors,
            smooth=self.ids.smooth.state)
        self.update_progress(self.shapes_detected, self.dedup_shapes)
        # Clock.schedule_once(self.dedup_shapes, 0)

    def dedup_shapes(self, *a):
        self.sequence.deduplicate_shapes()
        self.summarize()

    def detect_dedup(self):
        Clock.schedule_once(functools.partial(self.update_progress, self.text_detecting, self.detect_shapes), 0)

    def start_computation(self):
        # self.detect_dedup()
        cascade = self.sequence.load_cascade(self.cascade_name)
        detect = self.sequence.detect_and_store_shapes_generator(cascade,
            draw_markers=False,
            scale_factor=self.scale_factor,
            min_neighbors=self.min_neighbors,
            smooth=self.smooth
            )



        content=ProgressContent()
        self.progress_dialog = MDDialog(
                                        content=content,
                                        title=self.text_progress,
                                        size_hint=(.5, .5),
                                        auto_dismiss=False
                                        )
        content.bind(size=content.setter('size'))
        # self.progress_dialog.add_action_button("Dismiss",
        #                               action=lambda *x: self.progress_dialog.dismiss())

        self.progress_dialog.open()

        if self.sequence.overlapping:
            dedup = self.sequence.deduplicate_shapes_generator()

            all = chaining.clock_chain([
                functools.partial(self.log_step, self.text_detecting),
                [detect, self.log_detect],
                functools.partial(self.log_step, self.text_dedup),
                [dedup, self.log_dedup],
                functools.partial(self.log_step, self.text_ready),
                self.summarize,
                self.show_first_image,
                self.progress_dialog.dismiss
            ],
            self.log_exception)
        else:
            all = chaining.clock_chain([
                functools.partial(self.log_step, self.text_detecting),
                [detect, self.log_detect],
                functools.partial(self.log_step, self.text_ready),
                self.summarize,
                self.show_first_image,
                self.progress_dialog.dismiss
            ],
                self.log_exception)

        all()

    def log_detect(self, r):
        self.progress_dialog.content.sublog.text = (self.text_shapes_detected + " : %s") % (r + 1)

    def log_dedup(self, r):
        dlg=self.progress_dialog.content
        dlg.sublog.text = (self.text_dedup + " : %s , %s") % (r['index']+1, r['index']+2)
        dlg.details.text = (self.text_keypoints + ' : %s') % r['keypoints']

    def log_step(self, msg):
        self.progress_dialog.content.log.text = str(msg)

    def log_exception(self, ex, *a):
        self.progress_dialog.content.log.text = "EXCEPTION:%s" % ex
        Clock.schedule_once(self.progress_dialog.dismiss, 5)

    @mainthread
    def update_progress(self, msg, next, *a):
        self.progress.text=msg
        Clock.schedule_once(next, 0)

    def summarize(self):
        self.status.text = """V:{:.2f} / #:{:d} / A:{:.2f}""".format(self.sequence.volume,
                                                                     self.sequence.count_unique_shapes,
                                                                     self.sequence.area_unique_shapes)

    def show_first_image(self):
        self.image_view.image = self.sequence.images[0]
        self.image_view.draw()

    def show_props_screen(self):
        wiz=self.parent.parent.parent
        # import pdb;pdb.set_trace()
        wiz.switch_to_sequence_props()

    def show_props(self):
        content = SequenceProps(location=self.sequence.location,
                                show_delete=True)
        content.data = self.sequence.metadata
        dlg = BDDialog( title=self.text_properties,
                       size_hint=(1,1), auto_dismiss=True)
        def handle(content):
            # content.data.write_metadata()
            dlg.dismiss()

        dlg.content = content
        dlg.content.bind(on_props_changed=handle,
                         on_delete_selected=self.on_delete_selected)
        dlg.open()

    def on_delete_selected(self, widget, *a):
        def on_delete():
            widget.dialog.dismiss()
            self.delete_me()

        yesno_box("Loeschen",
                  "Soll diese Aufnahme wirklich geloescht werden?",
                  on_yes=on_delete,
                  )

    def delete_me(self):
        """deletes the current sequence, navigates to overview"""
        print("delete selected!!")
        sname, sid=self.sequence.name, self.sequence.id
        self.project.sequences.delete_sequence(self.sequence)
        self.dispatch("on_sequence_deleted", sid, sname)
        # import pdb;pdb.set_trace()


    def options_dialog(self):
        # import pdb;pdb.set_trace()
        print("options dialog")
        dialog = BDDialog(title=self.text_options,
                          auto_dismiss=True,
                          size_hint=(.8, .8),)

        # import pdb;pdb.set_trace()
        options = SequenceImageDetectionOptions(
                          scale_factor=self.scale_factor,
                          min_neighbors=self.min_neighbors,
                          cascade_names=self.sequence.list_cascades(),
                          cascade_name=self.cascade_name,
                          smooth=self.smooth
                        )

        def on_options(*a):
            # import pdb;pdb.set_trace()
            self.scale_factor = options.ids.scale_factor.value
            self.min_neighbors = options.ids.min_neighbors.value
            self.cascade_name = options.ids.cascades_list.text
            self.smooth = options.ids.smooth.active
            dialog.dismiss()

        dialog.add_action_button("Ok", on_options)
        dialog.content = options
        dialog.open()

    def on_share(self):
        location=self.sequence.location
        name=self.sequence.name
        service_provider = self.sequence.metadata.get('service_provider')
        length = self.sequence.length
        volume = int(np.round(self.sequence.volume))
        comment = self.sequence.metadata.get('comment','')

        url="http://maps.google.com/?q=%s,%s" % location

        msg="""
Polter:%s
Dienstleister:%s
Laenge:%s
FM:%s
%s
%s
"""     % (name, service_provider, length, volume, comment, url)

        # print 'share!:',msg
        self.share(msg)

    def share(self, msg):
        print('share msg:', msg)

        if platform != 'android':
            print('only android is supported, you have:', platform)
            return

        intent = Intent()
        intent.setAction(Intent.ACTION_SEND)
        intent.putExtra(Intent.EXTRA_TEXT, String(msg))
        intent.setType('text/plain')
        chooser = Intent.createChooser(intent, String("Polterinformation"))
        PythonActivity.mActivity.startActivity(chooser)

    def on_capture_dependent_sequence(self):
        id=str(uuid.uuid4())
        print('new dep seq',id, self.sequence.id)
        data={
            'name':self.sequence.name+"'",
            'service_provider':self.sequence.metadata['service_provider'],
            'comment':self.sequence.metadata.get('comment','')
        }

        self.dispatch('on_new_dependent_sequence', id, self.sequence.id, data, self.sequence)


Builder.load_string("""
<SequenceScreen>:
    id:sequence_view
    do_default_tab:False
    # MDTab:
    #     id:screen_sequence_view
    #     name:'screen_sequence_view'
    #     text:'view'
            
    SequenceView:
        id:sequence_view
        sequence: root.sequence
        path: root.sequence_path
        project_path:root.project_path  # for cascades dropdown
        project:root.project
        sequence_path:root.sequence_path
        on_new_dependent_sequence: root.new_dependent_sequence(*args)
        on_sequence_deleted:root.sequence_deleted(args[1],args[2])
        
    # TabbedPanelItem:
    #     id:screen_editor
    #     name:'screen_editor'
    #     text:'editor'
    #     ImageBrowser:
    #         id:sequence_images
    #         path: root.sequence_path
    #         project_path:root.project_path  # for cascades dropdown
    #         sequence_path:root.sequence_path

""")


class SequenceScreen(BoxLayout):
    """view class for a single sequence"""
    project = ObjectProperty()
    path = StringProperty()
    project_path = StringProperty()
    sequence_path = StringProperty()
    sequence = ObjectProperty()

    def __init__(self, **kw):
        super().__init__(**kw)
        self.register_event_type("on_sequence_deleted")

    def sequence_deleted(self, sid, name):
        print("sequence_deleted: ", sid, name)
        self.dispatch("on_sequence_deleted", sid, name)

    def on_sequence_deleted(self, *a):
        """"""

    def on_sequence(self, *a):
        # import pdb;pdb.set_trace()
        if 'sequence_images' in self.ids:
            self.ids.sequence_images.path = self.sequence.path

    def reload(self, **kw):
        self.sequence.load(load_img_data=True)
        self.ids.sequence_view.reload(**kw)

    def new_dependent_sequence(self, widget, id, ref_id, data, orig_sequence):
        print('new dependent seq', id, ref_id)
        wiz=self.parent.parent
        wiz.capture_sequence(id, ref_id, data, orig_sequence)

from ui.kivy.editor import ImageBrowser


Builder.load_string("""
<SequenceEditorScreen>:
    id:screen_editor
    name:'screen_editor'
    text:'editor'
    ImageBrowser:
        id:sequence_images
        path: root.sequence_path
        project_path:root.project_path  # for cascades dropdown
        sequence_path:root.sequence_path
""")


class SequenceEditorScreen(BoxLayout):
    """"""
    project = ObjectProperty()
    path = StringProperty()
    project_path = StringProperty()
    sequence_path = StringProperty()
    sequence = ObjectProperty()

    def on_sequence(self, *a):
        # import pdb;pdb.set_trace()
        if 'sequence_images' in self.ids:
            self.ids.sequence_images.path = self.sequence.path

    def reload(self, **kw):
        self.sequence.load(load_img_data=True)
        self.ids.sequence_view.reload(**kw)


Builder.load_string("""
<SequenceWizard>:
    props:props
    capture:capture
    sequence_images:sequence_images
    sequences_list:sequences_list
    
    Screen:
        name:'screen_list'
        SequencesList:
            id:sequences_list
            # sequences_path: root.sequences_path
            on_new_sequence: root.capture_sequence()
            on_sequence_selected: root.open_sequence(args[1])
            
    Screen:
        # map view for sequences
        id:map_screen
        name:'screen_map'
            
    Screen:
        name:'screen_props'
        SequenceProps:
            id:props
            data:root.sequence.metadata if root.sequence else {}
            on_props_changed: root.switch_to_sequence_view()
            
    Screen:
        name:'screen_capture'
        SequenceCapture:
            id:capture
            on_capture_done:root.switch_to_sequence_view()

    Screen:
        name:'screen_sequence_view'
        SequenceScreen:
            id:sequence_images
            sequence: root.sequence
            path: root.sequence_path
            project: root.project
            project_path:root.project_path  # for cascades dropdown
            on_sequence_deleted: root.sequence_deleted(args[1], args[2])
    Screen:
        name:'screen_sequence_editor'
        SequenceEditorScreen:
            id:sequence_image_editor
            sequence: root.sequence
            path: root.sequence_path
            project: root.project
            project_path:root.project_path  # for cascades dropdown

""")


class SequenceWizard(ScreenManager):
    """"""
    project = ObjectProperty()
    project_path = StringProperty()
    sequences_path = StringProperty()
    sequence = ObjectProperty(None)
    sequence_path = StringProperty()
    sequence_container=ObjectProperty()

    text_new_pile = _('new pile')

    def on_sequence(self, *a, **kw):
        # print 'SequenceWizard::on_sequence:', a, kw
        self.sequence_path=self.sequence.path
        # print '!!!!!!:', self.sequence.metadata
        self.ids.props.data=self.sequence.metadata

    def sequence_deleted(self, sid, name):
        self.switch_to_list()

    def on_project(self, *a, **kw):
        print('SequenceWizard::on_path:', a, kw)
        self.project_path = self.project.path
        self.capture.project = self.project
        self.sequences_path = self.project.sequences_path
        self.sequence_container = self.project.sequence_container(self.project.sequences_path)
        self.switch_to_list()

    def switch_to_new_sequence(self):
        self.current='screen_props'

    def switch_to_sequence_props(self):
        self.current='screen_props'
        # import pdb;pdb.set_trace()
        self.ids.props.data=self.sequence.metadata

    def switch_to_capture(self, props, id=None, ref_id=None, orig_sequence=None, *a):
        self.sequence = self.project.sequences.sequence(props.ids.name.text,
                                                        create=True,
                                                        metadata=props.data,
                                                        id=id,
                                                        ref_id=ref_id)
        if orig_sequence:
            orig_sequence.next_id=id
        self.capture.sequence = self.sequence
        self.ids.capture.init_cam()
        print('new sequence:', self.sequence.name)
        self.current = 'screen_capture'

    def switch_to_sequence_view(self):
        """switch to editor view"""
        self.current = 'screen_sequence_view'
        self.sequence_images.reload(incremental=False)

    def switch_to_editor(self):
        """switch to editor view"""
        self.current = 'screen_sequence_editor'
        self.sequence_images.reload(incremental=False)

    def switch_to_list(self):
        self.current = 'screen_list'
        self.sequence_container=self.project.sequence_container(self.sequences_path)
        self.sequences_list.sequences=self.sequence_container
        self.sequences_list.load()

    def init_map_screen(self, force_new=False):
        """creates the map view on first access"""
        if force_new or ('map_view' not in self.ids):
            mapview=SequencesMapView(self.sequence_container)
            mapview.bind(on_sequence_selected=lambda widget, sequence:self.open_sequence(sequence))

            self.ids.map_screen.add_widget(mapview)
            self.ids['map_view']=mapview

    def switch_to_map(self):
        """open map view"""
        self.current='screen_map'
        # import pdb;pdb.set_trace()
        self.sequence_container=self.project.sequence_container(self.sequences_path)

        self.init_map_screen()
        # TODO: self.ids.screen_map_view initialisieren

    def open_sequence(self, name):
        self.sequence = self.project.sequences.sequence(name, do_load=True)
        self.ids.props.data=self.sequence.metadata
        # import pdb;pdb.set_trace()
        self.current = 'screen_sequence_view'

    def open_screen(self, screen_name):
        self.current = screen_name

    def capture_sequence(self, id=None, ref_id=None, data=None, orig_sequence=None):
        if data is None:
            data={}
        content = SequenceProps()
        content.data = data
        dlg = BDDialog(title=self.text_new_pile, size_hint=(1,1), auto_dismiss=True)
        def handle(content):
            content.read_fields()
            self.switch_to_capture(content, id=id, ref_id=ref_id, orig_sequence=orig_sequence)
            dlg.dismiss()
        dlg.content=content
        content.bind(on_props_changed=handle)
        dlg.open()