Ejemplo n.º 1
0
    def show_history(self, sender):
        items = []
        for date, result in self.history.items():
            items.append({
                "title": "{}: {}".format(date.strftime("%Y-%m-%d %H:%M:%S"), result),
            })

        dialogs.list_dialog(title="История", items=items, multiple=False)
Ejemplo n.º 2
0
def completeReminder():

    _title = sys.argv[1] if len(sys.argv) > 1 else None
    _list = sys.argv[2] if len(sys.argv) > 2 else None

    if _list:
        calendars = reminders.get_all_calendars()
        _list = [x for x in calendars if x.title == _list]
        _list_title = _list[0].title
        todo = reminders.get_reminders(completed=False, calendar=_list[0])
        callback = 'twodo://x-callback-url/showList?name=%s' % quote(
            _list_title)
    else:
        todo = reminders.get_reminders(completed=False)
        callback = 'twodo://'

    if len(todo) == 0:
        return dialogs.hud_alert('You don\'t have any reminder left to do.')

    if _title:

        this = [x for x in todo if x.title == _title]

        if len(this) == 1:
            this = this[0]
        elif len(this) <= 0:
            return dialogs.hud_alert(
                'You don\'t have any reminder matching these terms.')
        else:
            todomap = {x.title: x for x in this}
            this = dialogs.list_dialog('Multiple matches', todomap.keys())

            if not this:
                return dialogs.hud_alert(
                    'You gotta pick the correct reminder.')
            else:
                this = todomap.get(this)

    else:
        todomap = {x.title: x for x in todo}
        this = dialogs.list_dialog('Multiple matches', todomap.keys())

        if not this:
            return dialogs.hud_alert('You gotta pick the correct reminder.')
        else:
            this = todomap.get(this)

    this.completed = True
    this.save()
    webbrowser.open(callback)
Ejemplo n.º 3
0
    def get_runtime_variable_for_parameter(self, parameter):
        rv = self.get_param_by_name('fm:runtime_variables')
        if rv == None:
            raise LookupError('Element requires fm:runtime_variables')

        keysavailablestring = ''
        for k in rv.value:
            keysavailablestring += k + ' '
        keysavailablemessage = 'Keys to choose from are: ' + keysavailablestring
        while parameter.variableName == None or parameter.variableName.replace(
                ' ', '') == '':
            try:
                key = dialogs.list_dialog('Vars', list(rv.value.keys()))
                parameter.variableName = key
            except:
                # if dialogs isnt available then fall back to console input
                parameter.variableName = console.input_alert(
                    title='Please enter variable title',
                    message=keysavailablemessage)
        if parameter.variableName in rv.value:
            parameter.value = copy.deepcopy(
                rv.value[parameter.variableName].value)
        else:
            raise KeyError('Parameter ' + parameter.variableName +
                           ' does not exist')
Ejemplo n.º 4
0
	def find_ssh_server(self, port):
		port_scan = Port_Scan(port, show_ip=False, alert=True)
		result = port_scan.scan()
		if len(result) == 0:
			return False
		elif len(result) == 1:
			return result[0]
		else:
			ip_dict = {}
			ip_list = []
			text = ''
			for ip in result:
				if ip in self.config:
					config = self.config[ip] 
					if 'name' in config and not config['name'] == '':
						name = config['name']
						text = 'Name : {} | IP : {}'.format(name, ip)
						if 'user' in config and not config['user'] == '':
							user = config['user']
							text += ' | User : {}'.format(user)					
					ip_dict[text] = ip
					ip_list.append(text)
				else:
					text = '{} ##first time##'.format(ip)
					ip_dict[text] = ip
					ip_list.append(text)
			_ip = dialogs.list_dialog('Port 22', ip_list)
			if _ip:
				ip = ip_dict[_ip]
				return ip
			else:
				return False
Ejemplo n.º 5
0
 def show_cmb_setup(self, sender):
     """shows the user a view to setup the controller keymap."""
     keymapname = dialogs.list_dialog("Select Keymap", [MSG_NEW_KEYMAP] +
                                      os.listdir(KEYMAPPATH), False)
     if keymapname is None:
         return
     if keymapname == MSG_NEW_KEYMAP:
         self.new_keymap()
     else:
         try:
             keymap = Keymap.load(keymapname)
         except:
             console.alert("Error",
                           "Cannot load Keymap!",
                           "Ok",
                           hide_cancel_button=True)
             return
         try:
             choice = console.alert(keymapname, "", "Select", "Edit",
                                    "Delete")
         except KeyboardInterrupt:
             return
         if choice == 1:
             self.map = keymap
         elif choice == 2:
             self.edit_keymap(keymap)
         elif choice == 3:
             try:
                 console.alert(
                     "Sure?",
                     "Are you sure you want to delete this keymap?",
                     "Delete")
             except KeyboardInterrupt:
                 return
             os.remove(os.path.join(KEYMAPPATH, keymapname))
Ejemplo n.º 6
0
def main():
    get_path = None
    if appex.is_running_extension() and appex.get_file_path():
        get_path = appex.get_file_path()
        if not re.match(r'.+\.(ipa|zip)$', get_path):
            console.hud_alert('Not supported file types', 'error', 1)
            appex.finish()
            exit()
    else:
        console.hud_alert('No file input', 'error', 1)
        appex.finish()
        exit()

    plist = extract_plist_data(get_path)
    if plist is None:
        console.hud_alert('No Info.plist file', 'error', 1)
        appex.finish()
        exit()
    else:
        url_schemes = extract_scheme(plist)
        if url_schemes:
            result = dialogs.list_dialog('Select to Clips', url_schemes)
            if result:
                clipboard.set(result + '://')
                console.hud_alert('Copied Success!', '', 1)
                appex.finish()
                exit()
            else:
                appex.finish()
                exit()
        else:
            console.hud_alert('No Url Schemes', 'error', 1)
            appex.finish()
            exit()
Ejemplo n.º 7
0
    def get_form_url(
        self,
        selections: List[str],
    ) -> Tuple[str, str]:
        links = [
            l for l in selections
            if (l != constants.FORM_BLANK and l != self.netloc)
        ]
        can_link = (self.is_reblog and links and not self.is_submission)
        if can_link:
            tag = dialogs.list_dialog(
                title='Which tag do you want to link?',
                items=links,
                multiple=False,
            ) or ''

            if tag:
                url = f'http://{self.netloc}/tagged/{tag}'
                url = re.sub(
                    constants.SPACES_RE,
                    '%20',
                    url,
                )

                url_text = (f'This tag "<strong>{tag}</strong>" ' +
                            'is 🔥!&nbsp;&#8250;')
                return url, url_text
        return ('', '')
Ejemplo n.º 8
0
def main():
    filename = editor.get_path()
    if not filename:
        dialogs.hud_alert('No file selected', 'error')
        return
    pyui_filename = os.path.splitext(filename)[0] + '.pyui'
    if not os.path.exists(pyui_filename):
        folder = os.path.split(filename)[0]
        files = os.listdir(folder)
        files = [f for f in files if f.endswith('.pyui')]
        if not files:
            dialogs.hud_alert('No pyui files found', 'error')
            return
        selected_pyui = dialogs.list_dialog('Select pyui file', files)
        if not selected_pyui:
            return
        pyui_filename = os.path.join(folder, selected_pyui)
    with open(pyui_filename, 'rb') as f:
        pyui = f.read()
    compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
    wrapped = '\n'.join(textwrap.wrap(compressed, 70))
    code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped, )
    clipboard.set(code)
    dialogs.hud_alert('Code copied', 'success')
Ejemplo n.º 9
0
def show_dialogs():
    items = [{
        "index": 0,
        "title": '全部重置',
        "action": all_init
    }, {
        "index": 1,
        "title": '修复数据库',
        "action": rebuild_db
    }, {
        "index": 2,
        "title": '删除缓存',
        "action": rm_cache
    }, {
        "index": 3,
        "title": '升级标签翻译',
        "action": update_ehtagtranslator_json
    }, {
        "index": 4,
        "title": '迁移到2.0',
        "action": transfer_to_v2
    }]
    result = dialogs.list_dialog(title='troublefix',
                                 items=list(map(lambda x: x['title'], items)),
                                 multiple=False)
    if result:
        action = next(filter(lambda x: x['title'] == result, items))['action']
        action()
Ejemplo n.º 10
0
def choose_assets():
    search = dialogs.input_alert('What is your album called?')

    albums = photos.get_albums()
    albums = list([a for a in albums if search in a.title])
    albums = list([a for a in albums if get_album_ends(a)[0] is not None])

    if len(albums) == 0:
        dialogs.hud_alert('No album found!', icon='error')
        return None

    album_names = [
        {
            'id':
            a.local_id,
            'index':
            i,
            'title':
            "{0} ({1})".format(a.title,
                               get_album_dates(a)[0].strftime('%b %d, %Y')),
            #'image': get_asset_thumb(get_album_ends(a)[0]),
            'accessory_type':
            'checkmark'
        } for (i, a) in enumerate(albums)
    ]
    album = dialogs.list_dialog('Choose Album', album_names)

    if album is None: return None

    album_index = album['index']
    assets = photos.pick_asset(albums[album_index], 'Choose Photos', True)

    return assets
Ejemplo n.º 11
0
    def post_reblog_original(self) -> None:
        client = self.get_client()
        post = self.get_post_from_post_id()
        tags = post.get('tags')
        reblog_key = self.get_reblog_key(post)
        comment = dialogs.text_dialog(title='Enter comment:', )
        state = dialogs.list_dialog(
            title='Reblog state:',
            items=constants.POST_STATES,
        )

        for blog in constants.BLOGS:
            response = client.reblog(
                blog,
                id=self.post_id,
                reblog_key=reblog_key,
                comment=comment,
                tags=tags,
                state=state,
            )
            if not response.get('id'):
                dialogs.alert(title='Error', message=pformat(response))

        print(
            'Reblogged to all blogs:',
            pformat(constants.BLOGS),
        )
Ejemplo n.º 12
0
def download(video_url):
    available_formats = []
    with youtube_dl.YoutubeDL({}) as ydl:
        meta = ydl.extract_info(video_url, download=False)
    formats = meta.get('formats', [meta])

    descriptions = ['Best']
    for format in formats:
        f = Format(format['format_id'], format['format'], format['ext'])
        available_formats.append(f)
        descriptions.append(f.description)
    selected_format = dialogs.list_dialog(title='Select a Format',
                                          items=descriptions)
    if selected_format is None:
        return
    format_to_use = 'best'
    ext = 'mp4'
    for format in available_formats:
        if selected_format == format.description:
            format_to_use = format.id
            ext = format.ext
    with youtube_dl.YoutubeDL({'format': format_to_use}) as ydl:
        ydl.download([video_url])

    list_of_files = glob.glob('*.*')
    latest_file = max(list_of_files, key=os.path.getctime)
    console.open_in(latest_file)
    if ext in latest_file:
        os.remove(latest_file)
Ejemplo n.º 13
0
	def show_flowtypeselection(self):
		self.selectedFlowType = self.flow_creation_view.data_source.flowType
		type = dialogs.list_dialog(title='Flow Type', items=['Normal','Action Extension'])
		if not type == None:
			self.selectedFlowType = type
		self.flow_creation_view.data_source.flowType = self.selectedFlowType
		self.flow_creation_view.reload_data()
Ejemplo n.º 14
0
def editpayload(payload):
    editing = True
    while editing:
        mainops = [{
            'title': 'Edit'
        }, {
            'title': 'Add Webclip'
        }, {
            'title': 'Add Wifi'
        }, {
            'title': 'Serve'
        }, {
            'title': 'Save'
        }] + payload.profile
        choice = dialogs.list_dialog('Profile', mainops)
        if choice == None:
            editing == False
            return payload
        if choice['title'] == 'Edit':
            payload.profile = dialogs.edit_list_dialog('Edit Profiles',
                                                       payload.profile)
        if choice['title'] == 'Add Webclip':
            webclip(payload)
        if choice['title'] == 'Add Wifi':
            wifi(payload)
        if choice['title'] == 'Serve':
            cpload = mprofile.mkplist(payload)
            serve.run_server(cpload)
        if choice['title'] == 'Save':
            name = dialogs.input_alert('File name')
            name = name + '.mobileconfig'
            cpload = mprofile.mkplist(pload)
            cpload = mprofile.stripdict(cpload)
            plistlib.writePlist(cpload, name)
    return payload
Ejemplo n.º 15
0
 def show_flowtypeselection(self):
     self.selectedFlowType = self.flow_creation_view.data_source.flowType
     type = dialogs.list_dialog(title="Flow Type", items=["Normal", "Action Extension"])
     if not type == None:
         self.selectedFlowType = type
     self.flow_creation_view.data_source.flowType = self.selectedFlowType
     self.flow_creation_view.reload_data()
Ejemplo n.º 16
0
def setdir(top):
    cwd = os.getcwd()
    files = os.listdir(cwd)
    dirs = []
    cwd_short = cwd.replace(top, "")
    dirs.append(".")
    dirs.append(".. " + cwd_short)
    for f in files:
        if os.path.isdir(f):
            dirs.append(f)
    #print(dirs)
    nextdir = dialogs.list_dialog("Select a directory", dirs, False, "Contiue")
    if nextdir is None:
        return (False)
    else:
        if nextdir.find("..") > -1:
            return (True)
        if nextdir.find(".") > -1:
            up = os.getcwd()
            up = up.rstrip("/")
            upend = up.rfind("/")
            up = up[0:upend]
            os.chdir(up)
            #			print("UP",up)
            return (setdir(top))
        os.chdir(cwd + "/" + nextdir)
        return (setdir(top))
Ejemplo n.º 17
0
	def tableview_did_select(self, tableview, section, row):
		param = self.params[row]
		name = param.displayName
		value = param.value
		if name == None or name == '':
			name = param.name
		if value == None:
			value = ''
		if param.type == 'string':
			param.value = console.input_alert(name, '', value)
		elif param.type == 'int':
			param.value = int(console.input_alert(name,'',str(value)))
		elif param.type == 'variable':
			pass
		elif param.type == 'list':
			ret = dialogs.list_dialog(title=name,items=param.allowedValues, multiple=param.multipleAllowed)
			yo = ''
			if not ret == None:
				if isinstance(ret,list):
					for item in ret:
						yo += item+','
				else:
					yo = ret
				yo = yo.rstrip(',')
			param.value = yo
		elif param.type == 'dictionary':
			self.dictionaryParam = param
			self.dictView = ElementParameterDictionaryInputView.get_view(dictionary=param.value, title=name, cb=self.dictionaryReturn, thememanager = self.thememanager)
			self.tv = tableview
			self.dictView.title_bar_color = self.thememanager.main_bar_colour
			self.dictView.tint_color = self.thememanager.main_tint_colour
			self.dictView.present(orientations=['portrait'])
		tableview.reload()
Ejemplo n.º 18
0
def search_for_movie(title: str, year: int, autopick=False):
    params = {'s': title, 'apiKey': OMDB_API_KEY, 'type': 'movie'}
    if year:
        params['y'] = year

    r = requests.get('http://www.omdbapi.com/', params=params)
    results = r.json()

    if is_pythonista:
        options = [{
            'title': f'{m["Title"]} ({m["Year"]})',
            'accessory_type': 'disclosure_indicator',
        } for m in results['Search']]

        chosen_title = dialogs.list_dialog('Pick one', options)
        if not chosen_title:
            return None

        chosen_index = options.index(chosen_title)
    elif autopick:
        chosen_index = 0
    else:
        options = [f'{m["Title"]} ({m["Year"]})' for m in results['Search']]
        [chosen_title, chosen_index] = pick(options)

    chosen_movie = results['Search'][chosen_index]

    return get_movie(chosen_movie['imdbID'])
Ejemplo n.º 19
0
def main():
	filename = editor.get_path()
	if not filename:
		dialogs.hud_alert('No file selected', 'error')
		return
	pyui_filename = os.path.splitext(filename)[0] + '.pyui'
	if not os.path.exists(pyui_filename):
		folder = os.path.split(filename)[0]
		files = os.listdir(folder)
		files = [f for f in files if f.endswith('.pyui')]
		if not files:
			dialogs.hud_alert('No pyui files found', 'error')
			return
		selected_pyui = dialogs.list_dialog('Select pyui file', files)
		if not selected_pyui:
			return
		pyui_filename = os.path.join(folder, selected_pyui)
	with open(pyui_filename, 'rb') as f:
		pyui = f.read()
	compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
	wrapped = '\n'.join(textwrap.wrap(compressed, 70))
	code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped,)
	clipboard.set(code)
	dialogs.hud_alert('Code copied', 'success')
Ejemplo n.º 20
0
 def ease_action(sender):
     global ease_function
     selection = dialogs.list_dialog('Select easing function',
                                     [func.__name__ for func in ease_funcs])
     if selection:
         ease_label.text = selection
         ease_function = globals()[selection]
         draw_ease(v)
Ejemplo n.º 21
0
def translate(sender):
    global translation
    show = dialogs.list_dialog("Translations", [trans for trans in translations])
    translation = show
    try:
        translation_label.text = translations[translation]
    except:
        None
Ejemplo n.º 22
0
def view_files(sender):
    global thoughts_file
    file_select = dialogs.list_dialog("Select A File", ["New"] + os.listdir("Notes"))
    if file_select == "New":
        thoughts_file = dialogs.input_alert("Name your thoughts file") + ".txt"
    elif file_select == None:
        pass
    else:
        thoughts_file = file_select
Ejemplo n.º 23
0
def translate(sender):
    global translation
    show = dialogs.list_dialog('Translations',
                               [trans for trans in translations])
    translation = show
    try:
        translation_label.text = translations[translation]
    except:
        None
Ejemplo n.º 24
0
def show_menu():
    choices = {
        '0: basic approach   ': method0,
        '1: activity indicator   ': method1,
        '2: hidden root     ': method2,
        '3: hidden subview/activity indicator': method3
    }
    choice = dialogs.list_dialog('select setup method', choices.keys())
    choices[choice]()
Ejemplo n.º 25
0
def pick_stbd_entry(sender):
	global v
	global possible_boats
	# make a list - add selection
	
	selected_boats_list = list_dialog(title = 'Select the Boats',items = possible_boats,multiple = False)
	
	p_b_ui = v['stbd_boat']
	p_b_ui.text = selected_boats_list
Ejemplo n.º 26
0
    def log(self):
        console.show_activity()
        try:
            url_match = re.match(
                r'^https?://(?:www\.)?imdb\.com/title/(tt\d+)/?',
                appex.get_url())
            params = {
                'api_key': self.moviedb_api,
                'external_source': 'imdb_id'
            }
            return self.getmovie(
                'https://api.themoviedb.org/3/movie/%s' % (url_match.group(1)),
                params)
        except TypeError:
            params = {
                'api_key':
                self.moviedb_api,
                'query':
                console.input_alert('Search for movie', '',
                                    sys.argv[1] if len(sys.argv) > 1 else '')
            }

            if len(params.get('query')) == 0:
                self.edit_config()
            else:
                req = requests.post(
                    'https://api.themoviedb.org/3/search/movie', params=params)

                if req.status_code == 200:
                    res = json.loads(req.text)

                    if res['total_results'] > 1:
                        results_map = {
                            e['title'] + self.getyear(e['release_date']): e
                            for e in res['results']
                        }
                        movie_pick = dialogs.list_dialog(
                            'Pick a movie', [
                                e['title'] + self.getyear(e['release_date'])
                                for e in res['results']
                            ])
                        if movie_pick is not None:
                            return self.getmovie(
                                'https://api.themoviedb.org/3/movie/%s' %
                                (results_map[movie_pick]['id']),
                                {'api_key': self.moviedb_api})
                        else:
                            raise NoMoviePickError()
                    elif res['total_results'] == 1:
                        return self.getmovie(
                            'https://api.themoviedb.org/3/movie/%s' %
                            (res['results'][0]['id']),
                            {'api_key': self.moviedb_api})
                    else:
                        raise NoResultsError()
                else:
                    raise TmdbConnectionError(req.text)
Ejemplo n.º 27
0
 def post_submission(self) -> None:
     client = self.get_client()
     blog = dialogs.list_dialog(
         title='Submissions from which blog?',
         items=constants.BLOGS,
         multiple=False,
     )
     submissions = client.submission(blog)
     dialogs.text_dialog(title='', text=pformat(submissions))
Ejemplo n.º 28
0
def view_files(sender):
    global thoughts_file
    file_select = dialogs.list_dialog('Select A File',
                                      ['New'] + os.listdir('Notes'))
    if file_select == 'New':
        thoughts_file = dialogs.input_alert('Name your thoughts file') + '.txt'
    elif file_select == None:
        pass
    else:
        thoughts_file = file_select
Ejemplo n.º 29
0
def ask_function(chan):
    lds = ui.ListDataSource([{
        'title': tm
    } for tm in datsrc.getFuncNames().values()])
    sel = dialogs.list_dialog('select function', lds.items)
    if sel:
        trg = float(vseti['target%d' % chan].text)
        set_func(chan, sel['title'])
        logger.info('setup func:%s for %d with %s' % (sel['title'], chan, trg))
        return sel['title']
Ejemplo n.º 30
0
	def present(self):
		actions = OrderedDict()
		actions['CLONE 	- Copy repo from Working Copy'] = self.copy_repo_from_wc
		actions['FETCH 	- Overwrite file with WC version'] = self.overwrite_with_wc_copy
		actions['PUSH 		- Send file to WC'] = self.push_current_file_to_wc
		actions['PUSH UI 	- Send associated PYUI to WC'] = self.push_pyui_to_wc
		actions['OPEN 		- Open repo in WC'] = self.open_repo_in_wc
		action = dialogs.list_dialog(title='Choose action', items=[key for key in actions])
		if action:
			actions[action]()
Ejemplo n.º 31
0
    def load_from(self):
        records = GameConfig.get_all_records()
        if len(records) == 0:
            return

        file = dialogs.list_dialog('Select record', list(records.keys()))
        if file is None:
            return
        hash = records[file]
        return self.load(f'{DIRNAME}/{hash}')
Ejemplo n.º 32
0
	def tableview_did_select(self, tableview, section, row):
		param = self.params[row]
		name = param.displayName
		value = param.value
		noVariable = True
		if param.isVariableAllowed:
			choice = console.alert(title='Variable Available', message = 'Would you like to choose a variable?', button1='Choose Variable', button2 = 'Ask when run', button3='Don\'t use a variable')
			if choice == 1:
				noVariable = False
				param.useVariable = True
				param.variableName = console.input_alert(title='Option',message='Please enter the variable name')
				param.value = None
				param.askAtRuntime = False
			elif choice == 2:
				noVariable = False
				param.useVariable = True
				param.value = None
				param.askAtRuntime = True
				param.variableName=''
			else:
				noVariable = True
				param.useVariable = False
				param.askAtRuntime = False
				param.variableName = ''
		if name == None or name == '':
			name = param.name
		if value == None:
			value = ''
		if noVariable and param.type == 'string':
			param.value = console.input_alert(name, '', value)
		elif noVariable and param.type == 'int':
			param.value = int(console.input_alert(name,'',str(value)))
		elif noVariable and param.type == 'variable':
			pass
		elif noVariable and param.type == 'list':
			ret = dialogs.list_dialog(title=name,items=param.allowedValues, multiple=param.multipleAllowed)
			yo = ''
			if not ret == None:
				if isinstance(ret,list):
					for item in ret:
						yo += item+','
				else:
					yo = ret
				yo = yo.rstrip(',')
			param.value = yo
		elif noVariable and param.type == 'dictionary':
			self.dictionaryParam = param
			self.dictView = ElementParameterDictionaryInputView.get_view(dictionary=param.value, title=name, cb=self.dictionaryReturn, thememanager = self.thememanager)
			self.tv = tableview
			self.dictView.title_bar_color = self.thememanager.main_bar_colour
			self.dictView.tint_color = self.thememanager.main_tint_colour
			self.dictView.present(orientations=['portrait'])
		elif noVariable and param.type == 'Boolean':
			pass
		tableview.reload()
Ejemplo n.º 33
0
def choose_theme(sender):
    light_themes = [None, "Default", "Dawn", "Tomorrow", "Solarized Light"]
    dark_themes = ["Solarized Dark", "Cool Glow", "Gold", "Tomorrow Night", "Oceanic", "Editorial"]
    thm_nm = dialogs.list_dialog("Themes", light_themes + dark_themes)
    if thm_nm in light_themes:
        for x in background_changes:
            x.background_color = "#fff"
    elif thm_nm in dark_themes:
        for x in background_changes:
            x.background_color = "#373737"
    editor.apply_ui_theme(bible, theme_name=thm_nm)
Ejemplo n.º 34
0
def delShortcut(bookpath):
    bookmarks = []
    for filename in os.listdir(bookpath):
        book = pickle.load(open(os.path.join(bookpath, filename), 'rb'))
        entry = {'title': book['album']['name'], 'filename': filename}
        bookmarks.append(entry)

    ans = dialogs.list_dialog(title="chose bookmark to delete",
                              items=bookmarks,
                              multiple=False)
    if ans:
        os.remove(os.path.join(bookpath, ans['filename']))
Ejemplo n.º 35
0
	def choose_color(self, b, name):
		"""called when the user wants to change a color."""
		section, option = name
		cur = b.background_color[:3]
		self.subview_open = True
		name = dialogs.list_dialog("Choose a color", COLORS, multiple=False)
		self.subview_open = False
		if name is None:
			return
		_stash.config.set(section, option, repr(name))
		self.table.reload_data()
		self.save()
Ejemplo n.º 36
0
 def choose_color(self, b, name):
     """called when the user wants to change a color."""
     section, option = name
     cur = b.background_color[:3]
     self.subview_open = True
     name = dialogs.list_dialog("Choose a color", COLORS, multiple=False)
     self.subview_open = False
     if name is None:
         return
     _stash.config.set(section, option, repr(name))
     self.table.reload_data()
     self.save()
Ejemplo n.º 37
0
    def getmovie(self, url, params):
        req = requests.get(url, params=params)

        if req.status_code == 200:
            res = json.loads(req.text)

            fields = {
                self.overview_field_name:
                res['overview'],
                self.title_field_name:
                res['title'],
                self.year_field_name:
                self.getyear(res['release_date'], True),
                self.date_field_name:
                self.getdate(),
                self.rating_field_name:
                dialogs.list_dialog("Rate '{0}'".format(res['title']), [
                    '★★★★★', '★★★★½', '★★★★', '★★★½', '★★★', '★★½', '★★', '★½',
                    '★', '½'
                ])
            }

            if self.cast_field or self.directors_field:
                credits = self.getcredits(url, params)
                if self.cast_field:
                    fields[self.cast_field_name] = credits[0]
                if self.directors_field:
                    fields[self.directors_field_name] = credits[1]

            if self.runtime_field:
                fields[self.runtime_field_name] = res['runtime']

            if self.imdb_field:
                fields[
                    self.
                    imdb_field_name] = 'http://www.imdb.com/title/%s/' % res[
                        'imdb_id']

            if self.genres_field:
                fields[self.genres_field_name] = self.getgenres(res['genres'])

            if res['poster_path'] is not None:
                fields[self.poster_field_name] = [{
                    'url':
                    'https://image.tmdb.org/t/p/original%s' %
                    res['poster_path']
                }]
            if fields[self.rating_field_name] is not None:
                return self.journal(fields)
            else:
                raise NoRatingError()
        else:
            raise TmdbConnectionError(req.text)
Ejemplo n.º 38
0
def change_color(sender):
    colors = [
        "black", "grey", "blue", "pink", "red", "green", "teal", "turquoise",
        "brown", "dodgerblue", "purple"
    ]
    endList = []
    for color in colors:
        endList.append({"title": color, "image": ui.Image('iob:record_24')})
    colorSwitcher = dialogs.list_dialog("Colors", endList)
    if colorSwitcher is not None:
        sender.tint_color = colorSwitcher["title"].lower()
        drawCanvas.color = colorSwitcher["title"].lower()
Ejemplo n.º 39
0
	def copy_repo_from_wc(self, repo_list=None):
		''' copy a repo to the local filesystem 
		'''
		if not repo_list:
			self._get_repo_list()
		else:
			repo_name = dialogs.list_dialog(title='Select repo', items=repo_list)
			if repo_name:
				action = 'zip'
				payload = {
					'repo': repo_name,
					'x-success': 'pythonista://{install_path}/Working_Copy_Sync.py?action=run&argv=copy_repo&argv={repo_name}&argv='.format(install_path=self.install_path, repo_name=repo_name)
				}
				self._send_to_working_copy(action, payload)
Ejemplo n.º 40
0
	def copy_repo_from_wc(self, repo_list=None):
		''' copy a repo to the local filesystem
		'''
		if not repo_list:
			self._get_repo_list()
		else:
			repo_name = dialogs.list_dialog(title='Select repo', items=repo_list)
			if repo_name:
				action = 'zip'
				fmt = '{pythonista_url}{install_path}/{wc_file}?action=run&argv=copy_repo&argv={repo_name}&argv='
				payload = {
					'repo': repo_name,
					'x-success': fmt.format(pythonista_url=PYTHONISTA_URL, install_path=self.install_path, repo_name=repo_name, wc_file=WC_FILENAME)
				}
				self._send_to_working_copy(action, payload)
Ejemplo n.º 41
0
def get_config():
	myconfdir = os.path.join(os.environ['HOME'], mlbConstants.AUTHDIR)
	myconf = os.path.join(myconfdir, AUTHFILE)
	mydefaults = {
		'video_player': DEFAULT_V_PLAYER,
		'audio_player': DEFAULT_A_PLAYER,
		'audio_follow': [],
		'alt_audio_follow': [],
		'video_follow': [],
		'blackout': [],
		'favorite': [],
		'use_color': 0,
		'adaptive_stream': 1,
		'favorite_color': 'cyan',
		'bg_color': 'xterm',
		'show_player_command': 0,
		'debug': 0,
		'x_display': '',
		'top_plays_player': '',
		'use_librtmp': 1,
		'use_nexdef': 0,
		'condensed': 0,
		'nexdef_url': 0,
		'zdebug': 0,
		'time_offset': '',
		'postseason': 1,
		'international': 1}

	config = MLBConfig(mydefaults)
	config.loads(myconf)
	if config.get('debug'):
		print 'Config: ' + repr(config.data)
	try:
		if not config.get('user'):
			config.set('user', dialogs.input_alert(title='Enter your MLB.tv username'))
		if not config.get('pass'):
			config.set('pass', dialogs.password_alert(
				title='Enter your MLB.tv password'))
		if not config.get('speed'):
			config.set('speed', dialogs.list_dialog(
				title='Select a speed (Kbps)', items=STREAM_SPEEDS))
	except KeyboardInterrupt:
		pass
	for prop in ['user', 'pass', 'speed']:
		if not config.get(prop):
			raise Exception(prop + ' is required')
	return config
Ejemplo n.º 42
0
	def show_cmb_setup(self, sender):
		"""shows the user a view to setup the controller keymap."""
		keymapname = dialogs.list_dialog(
			"Select Keymap",
			[MSG_NEW_KEYMAP] + os.listdir(KEYMAPPATH),
			False
			)
		if keymapname is None:
			return
		if keymapname == MSG_NEW_KEYMAP:
			self.new_keymap()
		else:
			try:
				keymap = Keymap.load(keymapname)
			except:
				console.alert(
					"Error",
					"Cannot load Keymap!",
					"Ok",
					hide_cancel_button=True
					)
				return
			try:
				choice = console.alert(
					keymapname,
					"",
					"Select",
					"Edit",
					"Delete"
					)
			except KeyboardInterrupt:
				return
			if choice == 1:
				self.map = keymap
			elif choice == 2:
				self.edit_keymap(keymap)
			elif choice == 3:
				try:
					console.alert(
						"Sure?",
						"Are you sure you want to delete this keymap?",
						"Delete"
						)
				except KeyboardInterrupt:
					return
				os.remove(os.path.join(KEYMAPPATH, keymapname))
Ejemplo n.º 43
0
	def run(self):
		np = self.get_param_by_name('VariableName')
		rv = self.get_param_by_name('fm:runtime_variables')
		keysavailablestring = ''
		for k in rv.value:
			keysavailablestring += k + ' '
		keysavailablemessage = 'Keys to choose from are: ' + keysavailablestring
		if (np.value or '').replace(' ', '') == '':
			try:
				key = dialogs.list_dialog('Vars',list(rv.value.keys()))
				self.name = key
			except :
				# if dialogs isnt available then fall back to console input
				self.name = console.input_alert(title='Please enter variable title', message=keysavailablemessage)
				
		else:
			self.name = np.value
		self.name = self.name or console.input_alert(title='Please enter variable title', message=keysavailablemessage)
		return rv.value[self.name].copyMe()
Ejemplo n.º 44
0
	def get_runtime_variable_for_parameter(self, parameter):
		rv = self.get_param_by_name('fm:runtime_variables')
		if rv == None:
			raise LookupError('Element requires fm:runtime_variables')
		
		keysavailablestring = ''
		for k in rv.value:
			keysavailablestring += k + ' '
		keysavailablemessage = 'Keys to choose from are: ' + keysavailablestring
		while parameter.variableName == None or parameter.variableName.replace(' ', '') == '':
			try:
				key = dialogs.list_dialog('Vars',list(rv.value.keys()))
				parameter.variableName = key
			except :
				# if dialogs isnt available then fall back to console input
				parameter.variableName = console.input_alert(title='Please enter variable title', message=keysavailablemessage)
		if parameter.variableName in rv.value:
			parameter.value = copy.deepcopy(rv.value[parameter.variableName].value)
		else:
			raise KeyError('Parameter ' + parameter.variableName + ' does not exist')
Ejemplo n.º 45
0
def editpayload(payload):
    editing = True
    while editing:
        mainops = [{'title':'Edit'},{'title':'Add Webclip'},{'title':'Add Wifi'},{'title':'Serve'},{'title':'Save'}]+payload.profile
        choice = dialogs.list_dialog('Profile',mainops)
        if choice == None:
            editing == False
            return payload
        if choice['title'] == 'Edit':
            payload.profile = dialogs.edit_list_dialog('Edit Profiles', payload.profile)
        if choice['title'] == 'Add Webclip':
            webclip(payload)
        if choice['title'] == 'Add Wifi':
            wifi(payload)
        if choice['title'] == 'Serve':
            cpload = profile.mkplist(payload)
            serve.run_server(cpload)
        if choice['title'] == 'Save':
            name = dialogs.input_alert('File name')
            name = name + '.mobileconfig'
            cpload = profile.mkplist(conf, pload)
            plistlib.writePlist(cpload, name)
    return
Ejemplo n.º 46
0
	def show_connection_setup(self, sender):
		"""shows the user a view to setup the connection."""
		if self.connected:
			do_disconnect = ask_disconnect()
			if do_disconnect:
				self.disconnect()
			else:
				return
		else:
			servers = self.discover()
			addresses = [a[1] + ":" + str(a[2]) for a in servers]
			to_show = [MSG_DIRECT_CONNECT] + addresses
			selected = dialogs.list_dialog(
				title="Select Server",
				items=to_show,
				multiple=False
				)
			if selected is None:
				return
			elif selected is MSG_DIRECT_CONNECT:
				self.do_direct_connect()
			else:
				self.connect(selected)
Ejemplo n.º 47
0
def setup():
    global email_user, email_pwd, v
    v = ui.load_view('myemail')
    send = ui.ButtonItem()
    send.title = 'Send'
    send.action = send_action
    v.right_button_items = [send]
    fromfield = v['fromfield']
    fromfield.text = email_user
    fromfield.scroll_enabled = False
    v['tofield'].clear_button_mode = 'while_editing'
    v['subjectfield'].clear_button_mode = 'while_editing'
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(email_user, email_pwd)
    v.present('sheet')

providers = dialogs.list_dialog(title='Select Your Email Provider', items=["Gmail", "AOL", "Yahoo!", "Comcast", "Outlook"], multiple=False)
if providers == 'Gmail':
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
elif providers == 'AOL':
    smtpserver = smtplib.SMTP("smtp.aol.com",587)
elif providers == 'Yahoo!':
    smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",587)
elif providers == 'Comcast':
    smtpserver = smtplib.SMTP("smtp.comcast.net",587)
elif providers == 'Outlook':
    smtpserver = smtplib.SMTP("smtp-mail.outlook.com",587)
login()
Ejemplo n.º 48
0
def load_or_save(action_in, save=None, reldir=None, filename=None):
    """
    Load/Save action input
    :param action_in: workflow action input
    :param save: bool switch to save or not
    :param reldir: relative path to folder containing the saved elements
    :param filename: filename to use (Python template format)
    :return: unicode action_out

    Usage from Editorial is:

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import workflow
    from editolido.workflows.lido2mapsme import load_or_save


    params = workflow.get_parameters()
    filename = params.get('Nom', '') or '{flight}_{departure}-{destination}_{date}_{datetime:%H:%M}z_OFP_{ofp}.txt'
    action_in = workflow.get_input()
    save = params.get('Sauvegarder', False)
    reldir = params.get('Dossier', '') or '_lido2mapsme_/data'
    workflow.set_output(load_or_save(action_in, save=save, reldir=reldir, filename=filename))
    """
    import console  # EDITORIAL module
    import dialogs  # EDITORIAL module

    from editolido.ofp import OFP
    ofp = None
    if action_in:
        ofp = OFP(action_in)
        if not ofp.infos:
            save = True  # force saving of unknown ofp
    if save and action_in:
        try:
            filename = filename.format(**ofp.infos)
        except TypeError:
            filename = '_ofp_non_reconnu_.kml'
            save_document(action_in, reldir, filename)
            print("OFP non reconnu, merci de créer un ticket (issue) sur:")
            print("https://github.com/flyingeek/editolido/issues")
            print("N'oubliez pas de joindre votre OFP en pdf.")
            print("Vous pouvez aussi le poster sur Yammer (groupe Mapsme)")
            raise KeyboardInterrupt
        else:
            save_document(action_in, reldir, filename)
    elif not action_in:  # Load
        try:
            files = os.listdir(get_abspath(reldir))
            if not files:
                raise OSError
        except OSError:
            console.alert('Aucune sauvegarde disponible',
                          'sauvegarder au moins une fois',
                          'Annuler',
                          hide_cancel_button=True)
            raise KeyboardInterrupt
        else:
            filename = dialogs.list_dialog('Choisir un fichier', files)
            if not filename:
                raise KeyboardInterrupt
            return load_document(reldir, filename)
    return action_in
Ejemplo n.º 49
0
Archivo: demo.py Proyecto: cclauss/ui2

def demo_delay():
    print('Starting')
    
    @ui2.delayed_by(2, id="Hello")
    def func():
        print("Finished")


# DEMO RUNNER -----------------------------------------------------------------


if __name__ == "__main__":
    import dialogs

    prefix = "demo_"

    # Generate list of demos
    functions = [k for k in globals().keys() if k.startswith(prefix)]

    # Let user pick one
    demo = dialogs.list_dialog(
        "Choose a demo",
        sorted([fn.replace(prefix, "").replace("_", " ") for fn in functions])
    )

    # Run the demo
    if demo is not None:
        globals()[prefix + demo]()
import editor
import os
import dialogs
import shutil

curdir=os.path.dirname(editor.get_path())

options=["iPads (non pro)",
		  "iPad Pro",
		  "iPhone 4, iPhone 4S",
		  "iPhone 5, iPhone 5S",
		  "iPhone 6, iPhone 6S",
		  "iPhone 6+, iPhone 6S+",
]

pyuiFiles=[
			"ipads-non-pro.pyui",
			"ipad-pro.pyui",
			"iphone-4,4S.pyui",
			"iphone-5,5S.pyui",
			"iphone-6,6S.pyui",
			"iphone-6+,iphone-6S+.pyui",
]

mapChoicesToFiles=dict(zip(options,pyuiFiles))

title="Choose a screen size"
choice=mapChoicesToFiles[ dialogs.list_dialog(title,options) ]

shutil.copy(choice,os.path.join(curdir,choice))
Ejemplo n.º 51
0

if __name__ == '__main__':
	try:
		if not live_player_is_installed():
			raise Exception('Please install Live Player')
		config = get_config()
		listings = get_listings(config)
		gamelist = sort_listings(config, listings)
		game = select_game(gamelist)
		items = [{
				'teamcode': k,
				'title': TEAMCODES[k][1]} for k in [game['hometeam'], game['awayteam']]]
		if game['national']:
			items.append({'teamcode': '0', 'title': 'National'})
		elif game['plus']:
			items.append({'teamcode': '+', 'title': 'MLB Plus'})
		team = dialogs.list_dialog(
			title='Select team broadcast',
			items=items)
		if not team:
			raise Exception('No broadcast selected')
		teamcode = team['teamcode']
		event_id = game['event_id']
		get_media(config=config, listings=listings, teamcode=teamcode,event_id_param=event_id)
		if config.get('debug'):
			sys.exit()
		serve_json_url()
	except Exception as e:
		dialogs.alert('Error: ' + str(e))
Ejemplo n.º 52
0
# coding: utf-8
from objc_util import *
import dialogs
import ClassBrowser

classes = ObjCClass.get_names()
ClassBrowser.main(cla=dialogs.list_dialog('Classes',classes))
Ejemplo n.º 53
0
def get_pyui_from_user():
    pyui_files = [f for f in os.listdir(os.curdir) if f.endswith(".pyui")]
    return dialogs.list_dialog(title="Pick a file", items=pyui_files)
Ejemplo n.º 54
0
 def type_action(self, sender):
     self.file_type = str(dialogs.list_dialog(title='Select a file type', items=[".txt", ".py", ".pyui"], multiple=False))
Ejemplo n.º 55
0
		'''detailview attribute.  set the splitview.detail=your_view to att your view to the detail'''
		return self._detailview
	@detailview.setter
	def detailview(self,value):
		if self._detailview:
			self._detailviewcontainer.remove_subview(self._detailview)
			self._detailview.splitview=None
		if value:
			self._detailview=value
			self._detailviewcontainer.add_subview(self._detailview)
			self._detailview.frame=self._detailviewcontainer.bounds
			self._detailview.splitview=self
	
if __name__=='__main__':
	import dialogs
	sz=dialogs.list_dialog('Choose view size',['iPhone','iPad'])
	if sz=='iPhone':
		frame=(0,0, 320, 440 )
	else:
		frame= (0, 0, 768,768)
	
	splitview=SplitView(frame=frame,bg_color=(1,1,1),initial_state=0)

	#create a mainview. could be loaded from pyui, etc
	mainview=ui.View(frame=splitview.bounds)
	tv=ui.TextView(frame=(100,100, frame[2]/2, frame[3]/2),bg_color=(.9,1,1),flex='wh')
	mainview.add_subview(tv)
	mainview.add_subview(ui.Button(name='menu',frame=(30,0,44,44),image=ui.Image.named('iob:drag_32')))
	def toggle(sender):
		splitview.toggle_detail()
	mainview['menu'].action=toggle