Пример #1
0
class Table(GridLayout):

    def __init__(self):
        super().__init__(cols=1)

        self.table = MDDataTable(use_pagination=True,
            column_data=[
                ("Name", dp(30)),
                ("Value", dp(30)),
                ("Date", dp(30)),
                ("Label", dp(30)),
                ("Debit/Credit", dp(30))],
            row_data=[
                (f"{i + 1}", f"{(i+1) * 2}", "2020-09-"+f"{i+1}".rjust(2, '0'), "Pastry", "Debit")
                for i in range(30)])

        self.add_widget(self.table)
        self.button = Button(text="Remove")
        self.add_widget(self.button)

        self.button.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_row_press=self.on_row_press)
        # self.remove_button.bind(on_press=callback)

    def on_row_press(self, instance_table, instance_row):
        print(instance_table, instance_row)

    def on_pressed(self, instance, touch):
        if touch.button == 'right':
            print('right mouse button clicked!')
Пример #2
0
    def askQuestion(self, question, answer='', cb=None,multiline=False):
        "As a text box based question, with optional  default answer.  If user confirm, call cb."

        t = MDTextField(text='', size_hint=(1,None),multiline=multiline,mode="rectangle")

        def nonsense(a):
            pass
        cb = cb or nonsense

        def cbr_yes(*a):
            print("Accept Button")
            cb(t.text)
            self.dialog.dismiss()

        def cbr_no(*a):
            cb(None)
            self.dialog.dismiss()

        self.dialog = MDDialog(
            type="custom",
            title=question,
            content_cls=t,
            buttons=[
                Button(
                    text="Accept", text_color=self.theme_cls.primary_color, on_press=cbr_yes
                ),
                Button(
                    text="Cancel", text_color=self.theme_cls.primary_color, on_press=cbr_no
                ),
            ],
        )
        #self.dialog.set_normal_height()

        t.text = answer
        self.dialog.open()
Пример #3
0
    def checkboxPrompt(self, question, answer=False, cb=None):
        "As a text box based question, with optional  default answer.  If user confirm, call cb."

        t = CheckBox(active=True)

        def cbr_yes(*a):
            cb(t.active)
            self.dialog.dismiss()

        def cbr_no(*a):
            cb(None)
            self.dialog.dismiss()

        self.dialog = MDDialog(
            type="custom",
            title=question,
            content_cls=t,
            buttons=[
                Button(text="Accept", on_press=cbr_yes),
                Button(text="Cancel", on_press=cbr_no),
            ],
        )
        self.dialog.height = (0.8, 0.8)
        t.active = answer
        self.dialog.open()
Пример #4
0
                def scope(info):
                    btn = Button(text="Open in Browser")

                    def f(*a):
                        self.openInBrowser("http://" + info['hash'] +
                                           ".localhost:7009")

                    btn.bind(on_press=f)

                    l.add_widget(btn)

                    btn = Button(text="Copy URL")

                    def f(*a):
                        try:
                            from kivy.core.clipboard import Clipboard
                            Clipboard.copy("http://" + info['hash'] +
                                           ".localhost:7009")
                        except:
                            logging.exception("Could not copy to clipboard")

                    btn.bind(on_press=f)

                    self.localServicesListBox.add_widget(
                        MDToolbar(title=str(info.get('title', 'no title'))))

                    l.add_widget(btn)
Пример #5
0
    def build(self):
        model_dir = Path("RFB-320")
        Logger.info(f"Model: Model directory path: {model_dir.__str__()}")
        self.model = cv2.dnn.readNetFromCaffe(
            Path(model_dir, "RFB-320.prototxt").__str__(),
            Path(model_dir, "RFB-320.caffemodel").__str__())
        Logger.info(f"Model: Model has loaded successfully ({self.model})")

        overlap_path = Path("Thug-Life-Glasses-PNG.png")
        self.overlap_image = cv2.imread(overlap_path.__str__(),
                                        cv2.IMREAD_UNCHANGED)
        self.overlap_image = cv2.resize(self.overlap_image, (320, 240))
        self.thug_life = False

        self.image_mean = np.array([127, 127, 127])
        self.image_std = 128.0
        self.iou_threshold = 0.3
        self.center_variance = 0.1
        self.size_variance = 0.2
        self.min_boxes = [[10.0, 16.0, 24.0], [32.0, 48.0], [64.0, 96.0],
                          [128.0, 192.0, 256.0]]
        self.strides = [8.0, 16.0, 32.0, 64.0]
        self.threshold = 0.7
        self.size_ratio = None

        self.input_size = (320, 240)
        self.width = self.input_size[0]
        self.height = self.input_size[1]
        self.priors = define_img_size(self.input_size)

        self.check_window_size()

        self.img1 = Image(pos_hint={'center_x': 0.5, 'center_y': 0.5})
        self.speed_button = Button(text="Change display size",
                                   size_hint=(0.2, 0.4),
                                   pos_hint={
                                       'center_x': 0.25,
                                       'center_y': 0.125
                                   })
        self.thug_button = Button(text="switch thug life",
                                  size_hint=(0.2, 0.4),
                                  pos_hint={
                                      'center_x': 0.75,
                                      'center_y': 0.125
                                  })
        self.thug_button.bind(on_press=self.switch_thug_life)
        self.speed_button.bind(on_press=self.set_display_speed)
        layout = FloatLayout(size=Window.size)
        layout.add_widget(self.img1)
        layout.add_widget(self.speed_button)
        layout.add_widget(self.thug_button)

        self.display_speed = 2  # 0 for best resolution, 1 for medium, 2 for fastest display
        desired_resolution = (720, 480)
        self.camCV = CameraCV(play=True, resolution=desired_resolution)
        self.camCV.image_bytes = False

        Clock.schedule_interval(self.update_texture, 1.0 / 60.0)
        return layout
Пример #6
0
 def __init__(self, **kwargs):
     super(grid, self).__init__(**kwargs)
     self.cols = 1
     self.inside = GridLayout()
     for device, val in devices.items():
         if (val['obj'].state):
             color = 1, 1, 1, 1
         else:
             color = .5, .5, .5, .5
         b = Button(text=device, font_size=40, color=color)
         b.bind(on_press=callback)
         self.add_widget(b)
Пример #7
0
    def makeSettingsPage(self):
        page = Screen(name='Settings')

        layout = BoxLayout(orientation='vertical')
        page.add_widget(layout)
        label = MDToolbar(title="Settings and Tools")
        layout.add_widget(label)

        layout.add_widget(self.makeBackButton())

        log = Button(text='System Logs')

        btn1 = Button(text='Local Services')
        label1 = Label(halign="center",
                       text='Share a local webservice with the world')

        log.bind(on_release=self.gotoLogs)
        btn1.bind(on_press=self.goToLocalServices)
        layout.add_widget(log)

        layout.add_widget(btn1)
        layout.add_widget(label1)

        btn = Button(text='Global Settings')

        btn.bind(on_press=self.goToGlobalSettings)
        layout.add_widget(btn)

        # Start/Stop
        btn3 = Button(text='Stop')
        btn3.bind(on_press=self.stop_service)
        label3 = Label(
            size_hint=(1, None),
            halign="center",
            text=
            'Stop the background process.  It must be running to acess hardline sites.  Starting may take a few seconds.'
        )
        layout.add_widget(btn3)
        layout.add_widget(label3)

        btn4 = Button(text='Start or Restart.')
        btn4.bind(on_press=self.start_service)
        label4 = Label(
            size_hint=(1, None),
            halign="center",
            text='Restart the process. It will show in your notifications.')
        layout.add_widget(btn4)
        layout.add_widget(label4)

        layout.add_widget(Widget())

        return page
Пример #8
0
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            Window.bind(on_keyboard=self.on_key)
            self.app = MDApp.get_running_app()
            self.screen_list = []
            self.nav_state = False
            self.store = JsonStore(
                os.path.join(abs_root, "assets", 'settings.json'))
            self.abs_root = abs_root
            self.logo = self.store.get("Settings")["Logo"]
            self.club_striped = self.strip_name()
            self.levels = levels

            #Used for global sheet manipulation
            self.sheet = None

            # Create folder
            from googleapiclient.discovery import build
            drive_service = build(u'drive',
                                  u'v3',
                                  credentials=self.get_creds())

            # Try to get sheet if accessable. Already handling the situation
            #where no sheet is loaded later in 'on_start' and 'changeScreen'
            try:
                self.sheet = self.get_spread()

                # Create needed folder(s)
                self.create_folders()

            except Exception as e:
                print(e)
                pass

            # Popup used for updates
            content = BoxLayout(orientation='vertical')
            label = Label(text=self.updates,
                          size_hint=(1, 0.5),
                          halign='center',
                          font_size='15sp')
            self.bind(updates=label.setter('text'))
            button = Button(text="OK", size_hint=(1, 0.5))
            content.add_widget(label)
            content.add_widget(button)
            size_hint = (.3, .3) if platform in 'win,linux' else (.6, .3)
            self.popup = Popup(title="Update",
                               content=content,
                               size_hint=size_hint,
                               auto_dismiss=True)
            button.bind(on_release=self.popup.dismiss)
Пример #9
0
class Color_Picker(Selection):
    colors = {"Sky Blue": (0.529, 0.808, 0.922)}

    browse_btn = Button(text="Browse")

    #browse_btn.bind(on_release=lambda x : x.root.browse(x))
    # bind button to static FileBrowser' browse() function
    #browse_btn.bind(on_release=lambda x : FileBrowser.open(FileBrowser.instance))

    def __init__(self, **kwargs):
        super(Color_Picker, self).__init__(**kwargs)
        # Layout for selecting items
        self.dropdown = DropDown()
        self.app = MDApp.get_running_app()
        self.picker_btn.text = "Choose Color"
        self.picker_btn.bind(on_release=self.dropdown.open)

        # Add colors to dropdown
        for color in self.colors:
            btn = Button(text=color, size_hint_y=None, height=40)
            # When a color is selected the name is passed to dropdown object
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self, 'selection', x))

    def dismiss(self):
        self.dropdown.dismiss()

    def on_leave(self):
        self.dropdown.clear_widgets()
Пример #10
0
    def __init__(self, **kwargs):
        super(Main_menu, self).__init__(**kwargs)

        Opt = Options()

        config = configparser.ConfigParser()
        config.read("settings.ini")
        name_interface = config['language']
        color_interface = config['colors']

        option = {
            0: lambda x: Opt.new_event(),
            1: lambda x: Opt.new_task(),
            2: lambda x: Opt.change_layout_calendar(),
            3: lambda x: Opt.change_layout_tasks()
        }
        name_options = {
            0: name_interface['new_event'],
            1: name_interface['new_task'],
            2: name_interface['change_layout_calendar'],
            3: name_interface['change_layout_tasks']
        }

        for i in range(len(name_options)):
            self.add_widget(
                Button(text=name_options[i],
                       on_press=option[i],
                       background_color=rgb(color_interface['menu_options']),
                       background_normal=''))
Пример #11
0
    def __init__(self, **kwargs):
        super(Color_Picker, self).__init__(**kwargs)
        # Layout for selecting items
        self.dropdown = DropDown()
        self.app = MDApp.get_running_app()
        self.picker_btn.text = "Choose Color"
        self.picker_btn.bind(on_release=self.dropdown.open)

        # Add colors to dropdown
        for color in self.colors:
            btn = Button(text=color, size_hint_y=None, height=40)
            # When a color is selected the name is passed to dropdown object
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.dropdown.bind(
            on_select=lambda instance, x: setattr(self, 'selection', x))
Пример #12
0
    def showQR(self, text,title="QR"):
        try:
            from kivy_garden.qrcode import QRCodeWidget
        except:
            logging.exception("Could not get QR lib")
            return self.showText(text,title)
        t =QRCodeWidget(data=text, size_hint=(1,1))
        t.size=(self.root_window.width/2, self.root_window.height/2.5)
        
        def cbr_yes(*a):
            print("Accept Button")
            self.dialog.dismiss()

    
        def cbr_txt(*a):
            print("Accept Button")
            self.dialog.dismiss()
            self.showText(text,title)

        def cbr_cpy(*a):
            print("Accept Button")
            self.dialog.dismiss()
            try:
                from kivy.core.clipboard import Clipboard
                Clipboard.copy(text)
            except:
                logging.exception("Could not copy to clipboard")

        self.dialog = MDDialog(
            type="custom",
            title=title,
            content_cls=t,
            buttons=[
                Button(
                    text="Close", text_color=self.theme_cls.primary_color, on_press=cbr_yes
                ),
                Button(
                    text="Show Text", text_color=self.theme_cls.primary_color, on_press=cbr_txt
                ),
                 Button(
                    text="Copy", text_color=self.theme_cls.primary_color, on_press=cbr_cpy
                )
            ],
        )
        #self.dialog.set_normal_height()
        self.dialog.open()
 def newbutton(text):
     button = Button(
         height=44,
         size_hint=(0.7, None),
         text=text,
         halign='center',
         valign='middle',
     )
     button.bind(size=button.setter('text_size'))
     return button
Пример #14
0
    def makeButtonForStream(self, name):
        "Make a button that, when pressed, edits the stream in the title"

        btn = Button(text=name)

        def f(*a):
            self.editStream(name)

        btn.bind(on_press=f)
        return btn
Пример #15
0
    def makeButtonForLocalService(self, name, c=None):
        "Make a button that, when pressed, edits the local service in the title"

        btn = Button(text=name)

        def f(*a):
            self.editLocalService(name, c)

        btn.bind(on_press=f)

        return btn
Пример #16
0
    def credits_button(self):
        global aperto
        if aperto == True:
            return
        content = GridLayout(rows=2)
        content.add_widget(
            MDLabel(text='''
This application acts as a support for the regulation of 
the carburetion of internal combustion engines.

[b]AutoCARB[/b] was developed by:
Davide Maieron and Adriano Mazzola 

With the collaboration of:
antipatico and Alessio Lei

The splash page and the icon are edited by:
Roberta Carlevaris

Contact: [email protected]
            ''',
                    padding_x=20,
                    markup=True,
                    theme_text_color="Custom",
                    text_color=(0.7, 0.5, 1, 1)))
        btn = Button(text="CLOSE", size_hint_y=None)
        content.add_widget(btn)
        pop = Popup(
            title='Credits',
            content=content,
            auto_dismiss=True,
            size_hint=(1, 1),
            separator_color=[0.7, 0.5, 1, 0.6],
            separator_height='5dp',
            title_align='center',
        )
        btn.bind(on_press=pop.dismiss)
        pop.bind(on_dismiss=self.check_pop_open)
        aperto = True
        pop.open()
        return
Пример #17
0
    def __init__(self):
        super().__init__(cols=1)

        self.table = MDDataTable(use_pagination=True,
            column_data=[
                ("Name", dp(30)),
                ("Value", dp(30)),
                ("Date", dp(30)),
                ("Label", dp(30)),
                ("Debit/Credit", dp(30))],
            row_data=[
                (f"{i + 1}", f"{(i+1) * 2}", "2020-09-"+f"{i+1}".rjust(2, '0'), "Pastry", "Debit")
                for i in range(30)])

        self.add_widget(self.table)
        self.button = Button(text="Remove")
        self.add_widget(self.button)

        self.button.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_row_press=self.on_row_press)
Пример #18
0
    def makeQuestionPage(self):

        # Discovery Page

        screen = Screen(name='question')
        self.discoveryScreen = screen

        layout = StackLayout(orientation="tb-lr",
                             spacing=10,
                             size_hint=(1, None))
        screen.add_widget(layout)

        self.questionLabel = label = self.saneLabel(text='', container=layout)

        self.questionTextbox = textbox = MDTextFieldRect(text='',
                                                         multiline=True,
                                                         size_hint=(0.68,
                                                                    None))
        layout.add_widget(self.questionLabel)

        layout.add_widget(textbox)

        def cbr_no(*a):
            self.screenManager.current = self.preQuestionScreen

        def cbr_yes(*a):
            self.screenManager.current = self.preQuestionScreen
            self.questionCallback(textbox.text)

        layout.add_widget(
            Button(text="Cancel",
                   text_color=self.theme_cls.primary_color,
                   on_press=cbr_no))
        layout.add_widget(
            Button(text="Accept",
                   text_color=self.theme_cls.primary_color,
                   on_press=cbr_yes))
        layout.add_widget(Widget())

        return screen
Пример #19
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'

        # Main screen layout
        screen_layout = MDGridLayout()
        screen_layout.cols = 2
        screen_layout.md_bg_color = [0, 1, 1, 1]

        # AC region
        self.timer = 0

        # AC Card
        new_layout = MDFloatLayout()
        self.ac_card1 = AcCard((0.75, 0.75))
        self.ac_card1.on_press = self.ac_touch_down
        self.ac_card1.on_release = self.ac_touch_up
        new_layout.add_widget(self.ac_card1)
        screen_layout.add_widget(new_layout)

        self.content = AcPopup()
        self.content.ac_card.on_release = partial(self.ac_touch_up, popup=True)

        self.ac_popup = Popup(title='AC settings', size_hint=(.75, .75))
        self.ac_popup.content = self.content
        self.ac_popup.background_color = [i / 255
                                          for i in [137, 205, 211]] + [1]

        #--------------------------------------------------------------#

        # Light setup
        new_layout = MDFloatLayout()
        self.light_card = MDCard(
            orientation='horizontal',
            padding='10dp',
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint=(0.75, 0.75),
        )
        self.light_card.md_bg_color = app.dark_color
        light_image = Image(
            source='static/light1.png',
            size_hint=(1, 1),
        )
        self.light_card.on_press = self.light_change
        self.light_card.add_widget(light_image)
        new_layout.add_widget(self.light_card)
        screen_layout.add_widget(new_layout)

        screen_layout.add_widget(Button(text='TODO'))
        screen_layout.add_widget(Button(text='TODO'))
        screen_layout.add_widget(Button(text='TODO'))
        screen_layout.add_widget(Button(text='TODO'))
        screen_layout.add_widget(Button(text='TODO'))
        screen_layout.add_widget(Button(text='TODO'))
        self.add_widget(screen_layout)
Пример #20
0
    def goToGlobalSettings(self, *a):
        if os.path.exists(hardline.globalSettingsPath):
            with open(hardline.globalSettingsPath) as f:
                globalConfig = toml.load(f)
        else:
            globalConfig = {}

        self.localSettingsBox.clear_widgets()

        self.localSettingsBox.add_widget(
            Label(size_hint=(1, 6), halign="center", text='OpenDHT Proxies'))
        self.localSettingsBox.add_widget(
            Label(size_hint=(1, None),
                  text='Proxies are tried in order from 1-3'))

        self.localSettingsBox.add_widget(
            self.settingButton(globalConfig, "DHTProxy", 'server1'))
        self.localSettingsBox.add_widget(
            self.settingButton(globalConfig, "DHTProxy", 'server2'))
        self.localSettingsBox.add_widget(
            self.settingButton(globalConfig, "DHTProxy", 'server3'))

        self.localSettingsBox.add_widget(
            Label(size_hint=(1, 6), halign="center", text='Stream Server'))
        self.localSettingsBox.add_widget(
            Label(
                size_hint=(1, None),
                text=
                'To allow others to sync to this node as a DrayerDB Stream server, set a server title to expose a service'
            ))

        self.localSettingsBox.add_widget(
            self.settingButton(globalConfig, "DrayerDB", 'serverName'))

        btn1 = Button(text='Save')

        def save(*a):
            with open(hardline.globalSettingsPath, 'w') as f:
                toml.dump(globalConfig, f)
            if platform == 'android':
                self.stop_service()
                self.start_service()
            else:
                daemonconfig.loadDrayerServerConfig()

            self.screenManager.current = "Main"

        btn1.bind(on_press=save)
        self.localSettingsBox.add_widget(btn1)
        self.screenManager.current = "GlobalSettings"
Пример #21
0
 def __init__(self, **kwargs):
     print("Before super")
     super(Selection, self).__init__(**kwargs)
     print("After super")
     self.orientation = "vertical"
     self.text_box = Label(text="...", color=(0, 0, 0, 1))
     #self.layout = BoxLayout(orientation='vertical')
     self.picker_btn = Button(text="Browse")
     self.add_widget(self.picker_btn)
     self.add_widget(self.text_box)
     # Set up background colors
     with self.text_box.canvas.before:
         Color(rbg=(1, 1, 1))
         self.text_box.rect = Rectangle(size=self.text_box.size,
                                        pos=self.text_box.pos)
     # Bind the background colors location to text_box
     self.text_box.bind(size=self.update_rect, pos=self.update_rect)
Пример #22
0
    def makeLocalServicesPage(self):

        screen = Screen(name='LocalServices')
        self.servicesScreen = screen

        layout = BoxLayout(orientation='vertical', spacing=10)
        screen.add_widget(layout)

        label = Label(
            size_hint=(1, None),
            halign="center",
            text=
            'WARNING: Running a local service may use a lot of data and battery.\nChanges may require service restart.'
        )

        labelw = Label(
            size_hint=(1, None),
            halign="center",
            text=
            'WARNING 2: This app currently prefers the external SD card for almost everything including the keys.'
        )

        layout.add_widget(self.makeBackButton())

        layout.add_widget(label)
        layout.add_widget(labelw)

        btn2 = Button(text='Create a service')

        btn2.bind(on_press=self.promptAddService)
        layout.add_widget(btn2)

        self.localServicesListBoxScroll = ScrollView(size_hint=(1, 1))

        self.localServicesListBox = BoxLayout(orientation='vertical',
                                              size_hint=(1, None),
                                              spacing=10)
        self.localServicesListBox.bind(
            minimum_height=self.localServicesListBox.setter('height'))

        self.localServicesListBoxScroll.add_widget(self.localServicesListBox)

        layout.add_widget(self.localServicesListBoxScroll)

        return screen
Пример #23
0
    def __init__(self, **kwargs):
        print("In FileBrowser")
        super(FileBrowser, self).__init__(**kwargs)
        self.app = MDApp.get_running_app()
        self.Browser = Popup(size_hint=(0.75, 0.75))
        fc = FileChooserListView()
        fc.rootpath = os.environ["PULSO_APP_ROOT"]
        exit = Button(text='Cancel',
                      size_hint=(1, 0.1),
                      on_release=self.Browser.dismiss)
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(fc)
        layout.add_widget(exit)
        self.Browser.add_widget(layout)

        fc.bind(selection=lambda instance, x: self.set_select(x))
        self.picker_btn.bind(
            on_release=lambda x: self.Browser.open(self.Browser))
Пример #24
0
    def showText(self, text,title="QR"):
       
        t= MDTextField(text=text, multiline=True,size_hint=(1,1),mode="rectangle")
        
        def cbr_yes(*a):
            print("Accept Button")
            self.dialog.dismiss()

        self.dialog = MDDialog(
            type="custom",
            title=title,
            content_cls=t,
            buttons=[
                Button(
                    text="Close", text_color=self.theme_cls.primary_color, on_press=cbr_yes
                )
            ],
        )
        #self.dialog.set_normal_height()
        self.dialog.open()
Пример #25
0
    def __init__(self, **kwargs):
        super(UCalendar, self).__init__(**kwargs)

        config = configparser.ConfigParser()
        config.read("settings.ini")

        wdays = config['weekdays']

        month, color = days_in_month()  # (list days in month)

        col = 7
        row = 5

        for i in range(row):
            for j in range(col):

                self.add_widget(
                    Button(
                        text=str(month[i][j]),
                        # on_press =
                        background_color=color[i][j],
                        background_normal=''))
Пример #26
0
    def makeRowWidget(self, stream, post):
        def f(*a):
            self.currentPageNewRecordHandler = None
            self.gotoStreamRow(stream, post['id'])

        l = BoxLayout(adaptive_height=True, orientation='vertical')
        l.add_widget(Button(text=post.get('name', "?????"), on_release=f))

        tlen = 0
        t = []
        for i in post:
            if i.startswith('row.') and not post[i] in (0, ''):
                x = i[4:] + ": " + str(
                    post[i])[:16] + ("..." if len(str(post[i])) > 16 else "")
                if tlen + len(x) > 120:
                    continue
                t.append(x)
                tlen += len(x)

        t = "\r\n".join(textwrap.wrap(",  ".join(t), 48))

        l.add_widget(self.saneLabel(t, l))
        return l
Пример #27
0
    def editStream(self, name):
        if not name in daemonconfig.userDatabases:
            self.goToStreams()
        db = daemonconfig.userDatabases[name]
        c = db.config
        try:
            c.add_section("Service")
        except:
            pass
        try:
            c.add_section("Info")
        except:
            pass

        self.streamEditPanel.clear_widgets()
        topbar = BoxLayout(size_hint=(1, None),
                           adaptive_height=True,
                           spacing=5)

        stack = StackLayout(size_hint=(1, None),
                            adaptive_height=True,
                            spacing=5)

        def upOne(*a):
            self.goToStreams()

        btn1 = Button(text='Up')

        btn1.bind(on_press=upOne)

        topbar.add_widget(btn1)

        topbar.add_widget(self.makeBackButton())

        self.streamEditPanel.add_widget(topbar)
        self.streamEditPanel.add_widget(MDToolbar(title=name))

        def goHere():
            self.editStream(name)

        self.backStack.append(goHere)
        self.backStack = self.backStack[-50:]

        btn2 = Button(text='Notebook View')

        def goPosts(*a):
            self.gotoStreamPosts(name)

        btn2.bind(on_press=goPosts)
        stack.add_widget(btn2)

        btn2 = Button(text='Feed View')

        def goPosts(*a):
            self.gotoStreamPosts(name, parent=None)

        btn2.bind(on_press=goPosts)
        stack.add_widget(btn2)

        btn2 = Button(text='Stream Settings')

        def goSettings(*a):
            self.editStreamSettings(name)

        btn2.bind(on_press=goSettings)
        stack.add_widget(btn2)

        if name.startswith('file:'):
            btn2 = Button(text='Close Stream')

            def close(*a):
                daemonconfig.closeUserDatabase(name)
                self.goToStreams()

            btn2.bind(on_press=close)
            stack.add_widget(btn2)

        importData = Button(text="Import Data File")

        def promptSet(*a):
            try:
                #Needed for android
                self.getPermission('files')
            except:
                logging.exception("cant ask permission")

            def f(selection):
                if selection:

                    def f2(x):
                        if x:
                            with daemonconfig.userDatabases[name]:
                                with open(selection) as f:
                                    daemonconfig.userDatabases[
                                        name].importFromToml(f.read())
                            daemonconfig.userDatabases[name].commit()

                    self.askQuestion("Really import?", "yes", cb=f2)
                self.openFM.close()

            from .kivymdfmfork import MDFileManager
            from . import directories
            self.openFM = MDFileManager(select_path=f)

            if os.path.exists("/storage/emulated/0/Documents") and os.access(
                    "/storage/emulated/0/Documents", os.W_OK):
                self.openFM.show("/storage/emulated/0/Documents")
            elif os.path.exists(
                    os.path.expanduser("~/Documents")) and os.access(
                        os.path.expanduser("~/Documents"), os.W_OK):
                self.openFM.show(os.path.expanduser("~/Documents"))
            else:
                self.openFM.show(directories.externalStorageDir
                                 or directories.settings_path)

        importData.bind(on_release=promptSet)
        stack.add_widget(importData)

        export = Button(text="Export All Posts")

        def promptSet(*a):
            from .kivymdfmfork import MDFileManager
            from .. import directories
            try:
                #Needed for android
                self.getPermission('files')
            except:
                logging.exception("cant ask permission")

            def f(selection):
                if selection:
                    if not selection.endswith(".toml"):
                        selection = selection + ".toml"

                    def g(a):
                        if a == 'yes':

                            r = daemonconfig.userDatabases[
                                name].getDocumentsByType('post', parent='')
                            data = daemonconfig.userDatabases[
                                name].exportRecordSetToTOML(
                                    [i['id'] for i in r])

                            logging.info("Exporting data to:" + selection)
                            with open(selection, 'w') as f:
                                f.write(data)
                        self.openFM.close()

                    if os.path.exists(selection):
                        self.askQuestion("Overwrite?", 'yes', g)
                    else:
                        g('yes')

            #Autocorrect had some fun with the kivymd devs
            self.openFM = MDFileManager(select_path=f,
                                        save_mode=(name + '.toml'))

            if os.path.exists("/storage/emulated/0/Documents") and os.access(
                    "/storage/emulated/0/Documents", os.W_OK):
                self.openFM.show("/storage/emulated/0/Documents")
            elif os.path.exists(
                    os.path.expanduser("~/Documents")) and os.access(
                        os.path.expanduser("~/Documents"), os.W_OK):
                self.openFM.show(os.path.expanduser("~/Documents"))
            else:
                self.openFM.show(directories.externalStorageDir
                                 or directories.settings_path)

        export.bind(on_release=promptSet)

        stack.add_widget(export)

        self.streamEditPanel.add_widget(stack)

        #Show recent changes no matter where they are in the tree.
        #TODO needs to be hideable for anti-spoiler purposes in fiction.
        self.streamEditPanel.add_widget(MDToolbar(title="Recent Changes:"))

        for i in daemonconfig.userDatabases[name].getDocumentsByType(
                'post', orderBy='arrival DESC', limit=5):
            x = self.makePostWidget(name, i, includeParent=True)
            self.streamEditPanel.add_widget(x)

        self.screenManager.current = "EditStream"
Пример #28
0
    def goToStreams(self, *a):

        "Go to a page wherein we can list user-modifiable services."
        self.streamsEditPanel.clear_widgets()

        layout = self.streamsEditPanel

        bar = BoxLayout(spacing=10, adaptive_height=True, size_hint=(1, None))

        stack = StackLayout(spacing=10,
                            adaptive_height=True,
                            size_hint=(1, None))
        layout.add_widget(bar)
        layout.add_widget(MDToolbar(title="My Streams"))

        layout.add_widget(stack)

        def upOne(*a):
            self.gotoMainScreen()

        btn1 = Button(text='Up')

        btn1.bind(on_press=upOne)

        bar.add_widget(btn1)
        bar.add_widget(self.makeBackButton())

        btn2 = Button(text='Create a Stream')

        btn2.bind(on_press=self.promptAddStream)
        stack.add_widget(btn2)

        def f(selection):
            if selection:
                dn = 'file:' + os.path.basename(selection)
                while dn in daemonconfig.userDatabases:
                    dn = dn + '2'
                try:
                    daemonconfig.loadUserDatabase(selection, dn)
                    self.editStream(dn)
                except:
                    logging.exception(dn)

            self.openFM.close()

        #This lets us view notebook files that aren't installed.
        def promptOpen(*a):

            try:
                #Needed for android
                self.getPermission('files')
            except:
                logging.exception("cant ask permission")

            from .kivymdfmfork import MDFileManager
            from . import directories
            self.openFM = MDFileManager(select_path=f)

            if os.path.exists("/storage/emulated/0/Documents") and os.access(
                    "/storage/emulated/0/Documents", os.W_OK):
                self.openFM.show("/storage/emulated/0/Documents")
            elif os.path.exists(
                    os.path.expanduser("~/Documents")) and os.access(
                        os.path.expanduser("~/Documents"), os.W_OK):
                self.openFM.show(os.path.expanduser("~/Documents"))
            else:
                self.openFM.show(directories.externalStorageDir
                                 or directories.settings_path)

        btn1 = Button(text='Open Book File')

        btn1.bind(on_press=promptOpen)

        stack.add_widget(btn1)

        def goHere():
            self.screenManager.current = "Streams"

        self.backStack.append(goHere)
        self.backStack = self.backStack[-50:]

        layout.add_widget(MDToolbar(title="Open Streams:"))

        try:
            s = daemonconfig.userDatabases
            time.sleep(0.5)
            for i in s:
                layout.add_widget(self.makeButtonForStream(i))
                try:
                    for j in daemonconfig.userDatabases[i].connectedServers:
                        if daemonconfig.userDatabases[i].connectedServers[
                                j] > (time.time() - (10 * 60)):
                            w = 'online'
                        else:
                            w = 'idle/offline'
                        layout.add_widget(
                            self.saneLabel(j[:28] + ": " + w, layout))
                except:
                    logging.exception("Error showing node status")

        except Exception:
            logging.info(traceback.format_exc())

        self.screenManager.current = "Streams"
Пример #29
0
    def editStreamSettings(self, name):
        db = daemonconfig.userDatabases[name]
        c = db.config

        self.streamEditPanel.clear_widgets()

        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None), halign="center", text=name))
        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None),
                  halign="center",
                  text="file:" + db.filename))

        self.streamEditPanel.add_widget(self.makeBackButton())

        def save(*a):
            logging.info("SAVE BUTTON WAS PRESSED")
            # On android this is the bg service's job
            db.saveConfig()

            if platform == 'android':
                self.stop_service()
                self.start_service()
            else:
                db.close()
                daemonconfig.loadUserDatabases(
                    None,
                    only=name,
                    callbackFunction=self.onDrayerRecordChange)

        def delete(*a):
            def f(n):
                if n and n == name:
                    daemonconfig.delDatabase(None, n)
                    if platform == 'android':
                        self.stop_service()
                        self.start_service()
                    self.goToStreams()

            self.askQuestion("Really delete?", name, f)

        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None),
                  halign="center",
                  font_size="24sp",
                  text='Sync'))

        self.streamEditPanel.add_widget(
            keyBox := self.settingButton(c, "Sync", "syncKey"))

        self.streamEditPanel.add_widget(
            pBox := self.settingButton(c, "Sync", "writePassword"))

        self.streamEditPanel.add_widget(
            Label(
                size_hint=(1, None),
                halign="center",
                font_size="12sp",
                text=
                'Keys have a special format, you must use the generator to change them.'
            ))

        def promptNewKeys(*a, **k):
            def makeKeys(a):
                if a == 'yes':
                    import base64
                    vk, sk = libnacl.crypto_sign_keypair()
                    vk = base64.b64encode(vk).decode()
                    sk = base64.b64encode(sk).decode()
                    keyBox.text = vk
                    pBox.text = sk

            self.askQuestion("Overwrite with random keys?", 'yes', makeKeys)

        keyButton = Button(text='Generate New Keys')
        keyButton.bind(on_press=promptNewKeys)
        self.streamEditPanel.add_widget(keyButton)

        self.streamEditPanel.add_widget(
            serverBox := self.settingButton(c, "Sync", "server"))

        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None),
                  halign="center",
                  text='Do not include the http:// '))

        self.streamEditPanel.add_widget(
            self.settingButton(c, "Sync", "serve", 'yes'))

        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None),
                  halign="center",
                  text='Set serve=no to forbid clients to sync'))

        self.streamEditPanel.add_widget(
            Label(size_hint=(1, None),
                  halign="center",
                  font_size="24sp",
                  text='Application'))

        self.streamEditPanel.add_widget(
            self.settingButton(c, "Application", "notifications", 'no'))

        def f(*a):
            def g(a):
                try:
                    import json
                    a = json.loads(a)
                    serverBox.text = c['Sync'][
                        'server'] = a['sv'] or c['Sync']['server']
                    keyBox.text = c['Sync']['syncKey'] = a['vk']
                    pBox.text = c['Sync']['writePassword'] = a['sk']

                except:
                    pass

            self.askQuestion("Enter Sharing Code", cb=g, multiline=True)

        keyButton = Button(text='Load from Code')
        keyButton.bind(on_press=f)
        self.streamEditPanel.add_widget(keyButton)

        def f(*a):
            self.showSharingCode(name, c)

        keyButton = Button(text='Show Sharing Code')
        keyButton.bind(on_press=f)
        self.streamEditPanel.add_widget(keyButton)

        def f(*a):
            self.showSharingCode(name, c, wp=False)

        keyButton = Button(text='Readonly Sharing Code')
        keyButton.bind(on_press=f)
        self.streamEditPanel.add_widget(keyButton)

        btn1 = Button(text='Save Changes')

        btn1.bind(on_press=save)
        self.streamEditPanel.add_widget(btn1)

        btn2 = Button(text='Delete this stream')

        btn2.bind(on_press=delete)
        self.streamEditPanel.add_widget(btn2)

        def gotoOrphans(*a, **k):
            self.gotoStreamPosts(name, orphansMode=True)

        oButton = Button(text='Show Unreachable Garbage')
        oButton.bind(on_press=gotoOrphans)
        self.streamEditPanel.add_widget(oButton)

        noSpreadsheet = Button(text="Spreadsheet on/off")

        def promptSet(*a):
            from .kivymdfmfork import MDFileManager
            from .. import directories
            try:
                #Needed for android
                self.getPermission('files')
            except:
                logging.exception("cant ask permission")

            def f(selection):
                if selection == 'on':
                    daemonconfig.userDatabases[
                        name].enableSpreadsheetEval = True
                else:
                    daemonconfig.userDatabases[
                        name].enableSpreadsheetEval = False

            if hasattr(daemonconfig.userDatabases[name],
                       'enableSpreadsheetEval'):
                esf = daemonconfig.userDatabases[name].enableSpreadsheetEval
            else:
                esf = True

            self.askQuestion("Allow Spreadsheet Functions?",
                             'on' if esf else 'off', f)

        noSpreadsheet.bind(on_release=promptSet)
        self.streamEditPanel.add_widget(noSpreadsheet)
        self.streamEditPanel.add_widget(
            self.saneLabel(
                "Disabling only takes effect for this session. Use this feature if a stream is loading too slowly, to allow you to fix the offending expression.",
                self.streamEditPanel))

        self.screenManager.current = "EditStream"
Пример #30
0
    def makeBackButton(self,width=1):
        btn1 = Button(text='Back')

        btn1.bind(on_press=self.goBack)
        return btn1