Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android file browser #1158

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions examples/filebrowser/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Android Filebrowser Demo
========================

Test app for the Android native file / folder chooser.

Quickstart
~~~~~~~~~~

For this example to work under Android, you need a briefcase android template
which supports onActivityResult in MainActivity.java
see https://github.com/t-arn/briefcase-android-gradle-template.git branch onActivityResult

To run this example:

$ pip install toga
$ python -m filebrowser
9 changes: 9 additions & 0 deletions examples/filebrowser/filebrowser/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '1.2.3rc1' # RC Release 1
# __version__ = '1.2.3' # Final Release
# __version__ = '1.2.3.post1' # Post Release 1

__version__ = '0.0.1'
4 changes: 4 additions & 0 deletions examples/filebrowser/filebrowser/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from filebrowser.app import main

if __name__ == '__main__':
main().main_loop()
125 changes: 125 additions & 0 deletions examples/filebrowser/filebrowser/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# For this example to work under Android, you need a briefcase android template
# which supports onActivityResult in MainActivity.java
# see https://github.com/t-arn/briefcase-android-gradle-template.git branch onActivityResult


import toga
from toga.style import Pack
from toga.constants import COLUMN, ROW
from rubicon.java import JavaClass

Intent = JavaClass("android/content/Intent")
Activity = JavaClass("android/app/Activity")


class ExampleFilebrowserApp(toga.App):
# Button callback functions
async def do_open_file(self, widget, **kwargs):
print("Clicked on 'Open file'")
multiselect = False
mimetypes = str(self.file_types.value).split(' ')
if self.multiselect.value == 'True':
multiselect = True
try:
selected_uri = ''
print(mimetypes)
if self.use_oifm.value != 'True':
selected_uri = await self.app.main_window.open_file_dialog("Choose a file", self.initial_dir.value,
mimetypes, multiselect)
else:
intent = Intent("org.openintents.action.PICK_FILE")
intent.putExtra("org.openintents.extra.TITLE", "Choose a file")
result = await self.app._impl.invoke_intent_for_result(intent)
print(str(result))
if result["resultData"] is not None:
selected_uri = result["resultData"].getData()
else:
selected_uri = 'No file selected, ResultCode was ' + str(result["resultCode"]) + ")"
except ValueError as e:
selected_uri = str(e)
print(str(selected_uri))
self.multiline.value = "You selected: \n" + str(selected_uri)

async def do_open_folder(self, widget, **kwargs):
print("Clicked on 'Open folder'")
multiselect = False
if self.multiselect.value == 'True':
multiselect = True
try:
selected_uri = ''
if self.use_oifm.value != 'True':
selected_uri = await self.app.main_window.select_folder_dialog("Choose a folder",
self.initial_dir.value, multiselect)
else:
intent = Intent("org.openintents.action.PICK_DIRECTORY")
intent.putExtra("org.openintents.extra.TITLE", "Choose a folder")
result = await self.app._impl.invoke_intent_for_result(intent)
print(str(result))
if result["resultData"] is not None:
selected_uri = result["resultData"].getData()
else:
selected_uri = 'No folder selected, ResultCode was ' + str(result["resultCode"]) + ")"
except ValueError as e:
selected_uri = str(e)
self.multiline.value = "You selected: \n" + str(selected_uri)

def do_clear(self, widget, **kwargs):
print('Clearing result')
self.multiline.value = "Ready."

def startup(self):
# Set up main window
self.main_window = toga.MainWindow(title=self.name, size=(400, 700))
flex_style = Pack(flex=1)

# set options
self.initial_dir = toga.TextInput(placeholder='initial directory', style=flex_style)
self.file_types = toga.TextInput(placeholder='MIME types (blank separated)', style=flex_style)
self.multiselect = toga.TextInput(placeholder='is multiselect? (True / False)', style=flex_style)
self.use_oifm = toga.TextInput(placeholder='Use OI Filemanager? (True / False)', style=flex_style)
# Toga.Switch does not seem to work on Android ...
# self.multiselect = toga.Switch('multiselect', is_on=False)
# self.use_oifm = toga.Switch('Use OI Filemanager')

# Text field to show responses.
self.multiline = toga.MultilineTextInput('Ready.', style=(Pack(height=200)))

# Buttons
btn_open_file = toga.Button('Open file', on_press=self.do_open_file, style=flex_style)
btn_open_folder = toga.Button('Open folder', on_press=self.do_open_folder, style=flex_style)
btn_clear = toga.Button('Clear', on_press=self.do_clear, style=flex_style)
btn_box = toga.Box(
children=[
btn_open_file,
btn_open_folder,
btn_clear
],
style=Pack(direction=ROW)
)

# Outermost box
outer_box = toga.Box(
children=[self.initial_dir, self.file_types, self.multiselect, self.use_oifm, btn_box, self.multiline],
style=Pack(
flex=1,
direction=COLUMN,
padding=10,
width=500,
height=300
)
)

# Add the content on the main window
self.main_window.content = outer_box

# Show the main window
self.main_window.show()


def main():
return ExampleFilebrowserApp('Android Filebrowser Demo', 'org.beeware.widgets.filebrowser')


if __name__ == '__main__':
app = main()
app.main_loop()
1 change: 1 addition & 0 deletions examples/filebrowser/filebrowser/resources/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Put any icons or images in this directory.
44 changes: 44 additions & 0 deletions examples/filebrowser/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
[build-system]
requires = ["briefcase"]

[tool.briefcase]
project_name = "Android Filebrowser Demo"
bundle = "org.beeware"
version = "0.3.0.dev25"
url = "https://beeware.org"
license = "BSD license"
author = 'Tiberius Yak'
author_email = "tiberius@beeware.org"

[tool.briefcase.app.filebrowser]
formal_name = "Android Filebrowser Demo"
description = "A testing app"
sources = ['filebrowser']
requires = []


[tool.briefcase.app.filebrowser.macOS]
requires = [
'toga-cocoa',
]

[tool.briefcase.app.filebrowser.linux]
requires = [
'toga-gtk',
]

[tool.briefcase.app.filebrowser.windows]
requires = [
'toga-winforms',
]

# Mobile deployments
[tool.briefcase.app.filebrowser.iOS]
requires = [
'toga-iOS',
]

[tool.briefcase.app.filebrowser.android]
requires = [
'toga-android',
]
35 changes: 35 additions & 0 deletions src/android/toga_android/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@
from .libs.activity import IPythonApp, MainActivity
from .window import Window

import asyncio


# `MainWindow` is defined here in `app.py`, not `window.py`, to mollify the test suite.
class MainWindow(Window):
pass


class TogaApp(IPythonApp):
last_intent_requestcode = -1 # always increment before using it for invoking new Intents
running_intents = {} # dictionary for currently running Intents

def __init__(self, app):
super().__init__()
self._interface = app
Expand Down Expand Up @@ -39,6 +44,20 @@ def onDestroy(self):
def onRestart(self):
print("Toga app: onRestart")

def onActivityResult(self, requestCode, resultCode, resultData):
"""
Callback method, called from MainActivity when an Intent ends

:param int requestCode: The integer request code originally supplied to startActivityForResult(),
allowing you to identify who this result came from.
:param int resultCode: The integer result code returned by the child activity through its setResult().
:param Intent resultData: An Intent, which can return result data to the caller (various data can be attached
to Intent "extras").
"""
print("Toga app: onActivityResult, requestCode={0}, resultData={1}".format(requestCode, resultData))
result_future = self.running_intents.pop(requestCode) # remove Intent from the list of running Intents
result_future.set_result({"resultCode": resultCode, "resultData": resultData})

@property
def native(self):
# We access `MainActivity.singletonThis` freshly each time, rather than
Expand Down Expand Up @@ -92,3 +111,19 @@ def set_on_exit(self, value):

def add_background_task(self, handler):
self.loop.call_soon(wrapped_handler(self, handler), self)

async def invoke_intent_for_result(self, intent):
"""
Calls an Intent and waits for its result

:param Intent intent: The Intent to call
:returns: A Dictionary containing "resultCode" (int) and "resultData" (Intent or None)
:rtype: dict
"""
self._listener.last_intent_requestcode += 1
code = self._listener.last_intent_requestcode
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a great use of counters to avoid object leaks, and excellent bookkeeping of the running_intents dict.

result_future = asyncio.Future()
self._listener.running_intents[code] = result_future
self.native.startActivityForResult(intent, code)
await result_future
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like to do return await result_future as one line, rather than two lines like you do here on 129-130. Your way is fine, too, so not a blocker, but just something that occurred to me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, I do not return result_future, I need to return result_future.result()
And return await result_future.result() did not work.

return result_future.result()
5 changes: 5 additions & 0 deletions src/android/toga_android/libs/android.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from rubicon.java import JavaClass

Activity = JavaClass("android/app/Activity")
Intent = JavaClass("android/content/Intent")
Uri = JavaClass("android/net/Uri")
87 changes: 87 additions & 0 deletions src/android/toga_android/window.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from . import dialogs
from .libs.android import Activity, Intent, Uri


class AndroidViewport:
Expand Down Expand Up @@ -78,3 +79,89 @@ def stack_trace_dialog(self, title, message, content, retry=False):

def save_file_dialog(self, title, suggested_filename, file_types):
self.interface.factory.not_implemented('Window.save_file_dialog()')

async def open_file_dialog(self, title, initial_uri, file_mime_types, multiselect):
"""
Opens a file chooser dialog and returns the chosen file as content URI.
Raises a ValueError when nothing has been selected

:param str title: The title is ignored on Android
:param initial_uri: The initial location shown in the file chooser. Must be a content URI, e.g.
'content://com.android.externalstorage.documents/document/primary%3ADownload%2FTest-dir'
:type initial_uri: str or None
:param file_mime_types: The file types allowed to select. Must be MIME types, e.g.
['application/pdf','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].
Currently ignored to avoid error in rubicon
:type file_mime_types: list[str] or None
:param bool multiselect: If True, then several files can be selected
:returns: The content URI of the chosen file or a list of content URIs when multiselect=True.
:rtype: str or list[str]
"""
print('Invoking Intent ACTION_OPEN_DOCUMENT')
intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.setType("*/*")
if initial_uri is not None and initial_uri != '':
intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(initial_uri))
if file_mime_types is not None and file_mime_types != ['']:
# Commented out because rubicon currently does not support arrays and nothing else works with this Intent
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @t-arn! This is a great change overall!

With regard to this line, it might be nice to file a rubicon-java bug requesting string arrays be passable-in somehow. Based on beeware/rubicon-java#53 it should be possible to do that.

It doesn't have to block this PR!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I filed a rubicon enhancement request:
beeware/rubicon-java#55

# see https://github.com/beeware/rubicon-java/pull/53
# intent.putExtra(Intent.EXTRA_MIME_TYPES, file_mime_types)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be worth putting in a NotImplemented call here so that the end-user sees a manifestation of this limitation in the logs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, will do

self.interface.factory.not_implemented(
'Window.open_file_dialog() on Android currently does not support the file_type parameter')
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiselect)
selected_uri = None
result = await self.app.invoke_intent_for_result(intent)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is awesome :D

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I also like that method. You can use it for calling any Intent you like.
In the example, I use it for calling the OI Filemanager Intents just to show how it can be used directly.

if result["resultCode"] == Activity.RESULT_OK:
if result["resultData"] is not None:
selected_uri = result["resultData"].getData()
if multiselect:
if selected_uri is None:
# when the user selects more than 1 file, getData() will be None. Instead, getClipData() will
# contain the list of chosen files
selected_uri = []
clip_data = result["resultData"].getClipData()
if clip_data is not None: # just to be sure there will never be a null reference exception...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - but why will there be a null reference exception? Docstrings should be about the why, not the what. Dif size == 3: # check if size is 3 doesn't tell me anything I couldn't work out by reading the code; # size 3 is prohibited by the standard tells me why the code exists.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, I'm not sure if there ever will be a null pointer exception.
On the other hand, I'm also not sure that clip_data will always be not-null when resultData is null...

for i in range(0, clip_data.getItemCount()):
selected_uri.append(str(clip_data.getItemAt(i).getUri()))
else:
selected_uri = [str(selected_uri)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it's not at the right indent level... is this the else for the multiselect?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the problem is that even when multiselect is True, the user might only select 1 file which will be returned with getData() (and clip_data will be empty). Only when multiselect is True AND the user selected several files, clip_data will contain the list with the files (and getData will be None)

if selected_uri is None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code smoothly handles the cancellation possibility!

raise ValueError("No filename provided in the open file dialog")
return selected_uri

async def select_folder_dialog(self, title, initial_uri=None, multiselect=False):
"""
Opens a folder chooser dialog and returns the chosen folder as content URI.
Raises a ValueError when nothing has been selected

:param str title: The title is ignored on Android
:param initial_uri: The initial location shown in the file chooser. Must be a content URI, e.g.
'content://com.android.externalstorage.documents/document/primary%3ADownload%2FTest-dir'
:type initial_uri: str or None
:param bool multiselect: If True, then several files can be selected
:returns: The content tree URI of the chosen folder or a list of content URIs when multiselect=True.
:rtype: str or list[str]
"""
print('Invoking Intent ACTION_OPEN_DOCUMENT_TREE')
intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
if initial_uri is not None and initial_uri != '':
intent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(initial_uri))
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiselect)
selected_uri = None
result = await self.app.invoke_intent_for_result(intent)
if result["resultCode"] == Activity.RESULT_OK:
if result["resultData"] is not None:
selected_uri = result["resultData"].getData()
if multiselect is True:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an analogous need for docstrings in this implementation; we can't assume someone will read both methods.

if selected_uri is None:
selected_uri = []
clip_data = result["resultData"].getClipData()
if clip_data is not None:
for i in range(0, clip_data.getItemCount()):
selected_uri.append(str(clip_data.getItemAt(i).getUri()))
else:
selected_uri = [str(selected_uri)]
if selected_uri is None:
raise ValueError("No folder provided in the open folder dialog")
return selected_uri
Loading