Format files (#1179)

use https://codeberg.org/qwerty287/woodpecker-intellij-formatter

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: M M Arif <mmarif@noreply.codeberg.org>
Co-authored-by: qwerty287 <ndev@web.de>
Reviewed-on: https://codeberg.org/gitnex/GitNex/pulls/1179
Reviewed-by: 6543 <6543@noreply.codeberg.org>
Co-authored-by: qwerty287 <qwerty287@noreply.codeberg.org>
Co-committed-by: qwerty287 <qwerty287@noreply.codeberg.org>
This commit is contained in:
qwerty287 2022-08-15 16:26:02 +02:00 committed by 6543
parent 151cb8429c
commit a7d9918b67
552 changed files with 15039 additions and 15130 deletions

View File

@ -13,6 +13,7 @@ line_comment = //
block_comment_start = /* block_comment_start = /*
block_comment = * block_comment = *
block_comment_end = */ block_comment_end = */
max_line_length = 220
[*.json] [*.json]
indent_size = 2 indent_size = 2

View File

@ -9,6 +9,7 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
##### What did you expect? ##### What did you expect?

View File

@ -9,6 +9,7 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/gitnex/GitNex/wiki/Contributing).

View File

@ -9,6 +9,7 @@ labels:
--- ---
## # Describe your matter briefly ## # Describe your matter briefly
<br><br> <br><br>
##### What did you expect? ##### What did you expect?

View File

@ -1,4 +1,5 @@
### Describe what your pull request does and which issue youre targeting ### Describe what your pull request does and which issue youre targeting
<!-- Create a new issue, if it doesn't exist yet --> <!-- Create a new issue, if it doesn't exist yet -->
<br><br> <br><br>
@ -6,4 +7,5 @@
- [ ] I carefully read the [contribution guidelines](https://codeberg.org/GitNex/GitNex/src/branch/main/CONTRIBUTING.md). - [ ] I carefully read the [contribution guidelines](https://codeberg.org/GitNex/GitNex/src/branch/main/CONTRIBUTING.md).
- [ ] I'm following the code standards as defined [here](https://codeberg.org/gitnex/GitNex/wiki/Code-Standards). - [ ] I'm following the code standards as defined [here](https://codeberg.org/gitnex/GitNex/wiki/Code-Standards).
- [ ] By submitting this pull request, I permit GitNex to license my work under the [GNU General Public License v3](https://codeberg.org/GitNex/GitNex/src/branch/main/LICENSE). - [ ] By submitting this pull request, I permit GitNex to license my work under
the [GNU General Public License v3](https://codeberg.org/GitNex/GitNex/src/branch/main/LICENSE).

View File

@ -16,24 +16,9 @@
</value> </value>
</option> </option>
</JavaCodeStyleSettings> </JavaCodeStyleSettings>
<JetCodeStyleSettings> <XML>
<option name="PACKAGES_TO_USE_STAR_IMPORTS"> <option name="XML_ALIGN_ATTRIBUTES" value="false"/>
<value> </XML>
<package name="java.util" alias="false" withSubpackages="false" />
<package name="kotlinx.android.synthetic" alias="false" withSubpackages="true" />
<package name="io.ktor" alias="false" withSubpackages="true" />
</value>
</option>
<option name="PACKAGES_IMPORT_LAYOUT">
<value>
<package name="" alias="false" withSubpackages="true" />
<package name="java" alias="false" withSubpackages="true" />
<package name="javax" alias="false" withSubpackages="true" />
<package name="kotlin" alias="false" withSubpackages="true" />
<package name="" alias="true" withSubpackages="true" />
</value>
</option>
</JetCodeStyleSettings>
<codeStyleSettings language="JAVA"> <codeStyleSettings language="JAVA">
<option name="RIGHT_MARGIN" value="220"/> <option name="RIGHT_MARGIN" value="220"/>
<option name="KEEP_LINE_BREAKS" value="false"/> <option name="KEEP_LINE_BREAKS" value="false"/>
@ -41,7 +26,6 @@
<option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false"/> <option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false"/>
<option name="BLANK_LINES_AROUND_FIELD_IN_INTERFACE" value="1"/> <option name="BLANK_LINES_AROUND_FIELD_IN_INTERFACE" value="1"/>
<option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1"/> <option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1"/>
<option name="BLANK_LINES_AFTER_ANONYMOUS_CLASS_HEADER" value="1" />
<option name="BLANK_LINES_BEFORE_CLASS_END" value="1"/> <option name="BLANK_LINES_BEFORE_CLASS_END" value="1"/>
<option name="ELSE_ON_NEW_LINE" value="true"/> <option name="ELSE_ON_NEW_LINE" value="true"/>
<option name="CATCH_ON_NEW_LINE" value="true"/> <option name="CATCH_ON_NEW_LINE" value="true"/>

View File

@ -1,6 +1,7 @@
pipeline: pipeline:
author-header: author-header:
image: qwerty287/woodpecker-regex-check image: qwerty287/woodpecker-regex-check
group: check
settings: settings:
pattern: "*.java" pattern: "*.java"
regex: " \\\\* \\\\@author [\\\\S\\\\s]+" regex: " \\\\* \\\\@author [\\\\S\\\\s]+"
@ -8,3 +9,7 @@ pipeline:
style: style:
image: qwerty287/woodpecker-intellij-formatter image: qwerty287/woodpecker-intellij-formatter
group: check
settings:
file_pattern: "*.java"
path: "app/"

View File

@ -1,2 +1,3 @@
# Changelog # Changelog
[Check out the release notes](https://codeberg.org/gitnex/GitNex/releases) [Check out the release notes](https://codeberg.org/gitnex/GitNex/releases)

View File

@ -4,26 +4,33 @@
# GitNex - Android client for Gitea # GitNex - Android client for Gitea
GitNex is a free/paid, open-source Android client for Git repository management tool Gitea. Gitea is a community managed fork of Gogs, lightweight code hosting solution written in Go. GitNex is a free/paid, open-source Android client for Git repository management tool Gitea. Gitea is a community managed fork of Gogs, lightweight
code hosting solution written in Go.
GitNex is licensed under GPLv3 License. See the LICENSE file for the full license text. **No trackers are used** and source code is available here for anyone to audit. GitNex is licensed under GPLv3 License. See the LICENSE file for the full license text. **No trackers are used** and source code is available here for
anyone to audit.
## Downloads ## Downloads
[<img alt='Get it on F-Droid' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/fdroid.png' height="80"/>](https://f-droid.org/en/packages/org.mian.gitnex/) [<img alt='Get it on F-Droid' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/fdroid.png' height="80"/>](https://f-droid.org/en/packages/org.mian.gitnex/)
[<img alt='Get it on Google Play' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/google-play.png' height="80"/>](https://play.google.com/store/apps/details?id=org.mian.gitnex.pro) [<img alt='Get it on Google Play' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/google-play.png' height="80"/>](https://play.google.com/store/apps/details?id=org.mian.gitnex.pro)
[<img alt='Download builds and releases' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/apk-badge.png' height="82"/>](https://cloud.swatian.com/s/DN7E5xxtaw4fRbE) [<img alt='Download builds and releases' src='https://codeberg.org/gitnex/GitNex/raw/branch/main/assets/apk-badge.png' height="82"/>](https://cloud.swatian.com/s/DN7E5xxtaw4fRbE)
## Note about Gitea version ## Note about Gitea version
Please make sure that you are on latest stable release or later for better app experience. Please make sure that you are on latest stable release or later for better app experience.
Check the versions [compatibility page](https://codeberg.org/gitnex/GitNex/wiki/Compatibility) which lists all the supported versions with compatibility ratio. Check the versions [compatibility page](https://codeberg.org/gitnex/GitNex/wiki/Compatibility) which lists all the supported versions with
compatibility ratio.
## Build from source ## Build from source
Option 1 - Download the source code, open it in Android Studio and build it there. Option 1 - Download the source code, open it in Android Studio and build it there.
Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assembleFree`. Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assembleFree`.
## Features ## Features
- Multiple accounts support - Multiple accounts support
- File and directory browser - File and directory browser
- File viewer - File viewer
@ -37,12 +44,15 @@ Option 2 - Open terminal(Linux) and cd to the project dir. Run `./gradlew assemb
- [& more...](https://codeberg.org/gitnex/GitNex/wiki/Features) - [& more...](https://codeberg.org/gitnex/GitNex/wiki/Features)
## Contributing ## Contributing
[Contributing](https://codeberg.org/gitnex/GitNex/wiki/Contributing) [Contributing](https://codeberg.org/gitnex/GitNex/wiki/Contributing)
## Translation ## Translation
Help us translate GitNex to your native language. Help us translate GitNex to your native language.
We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your language is not listed, please request [here](https://codeberg.org/gitnex/GitNex/issues) to add it to the project. We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your language is not listed, please
request [here](https://codeberg.org/gitnex/GitNex/issues) to add it to the project.
**Link: https://crowdin.com/project/GitNex** **Link: https://crowdin.com/project/GitNex**
@ -53,6 +63,7 @@ We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your la
[<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png" alt="005.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png" alt="006.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png" alt="007.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png" alt="008.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png) [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png" alt="005.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/005.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png" alt="006.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/006.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png" alt="007.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/007.png) | [<img src="https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png" alt="008.png" width="200"/>](https://codeberg.org/gitnex/GitNex/raw/branch/main/fastlane/metadata/android/en-US/images/phoneScreenshots/008.png)
## Links ## Links
[Website](https://gitnex.com) [Website](https://gitnex.com)
[Wiki](https://codeberg.org/gitnex/GitNex/wiki/Home) [Wiki](https://codeberg.org/gitnex/GitNex/wiki/Home)
@ -64,9 +75,11 @@ We use [Crowdin](https://crowdin.com/project/gitnex) for translation. If your la
[Release Blog](https://gitnex.codeberg.page) [Release Blog](https://gitnex.codeberg.page)
## Thanks ## Thanks
Thanks to all the open source libraries, contributors and donators. Thanks to all the open source libraries, contributors and donators.
#### Open source libraries #### Open source libraries
- [square/retrofit](https://github.com/square/retrofit) - [square/retrofit](https://github.com/square/retrofit)
- [google/gson](https://github.com/google/gson) - [google/gson](https://github.com/google/gson)
- [square/okhttp](https://github.com/square/okhttp) - [square/okhttp](https://github.com/square/okhttp)
@ -89,6 +102,7 @@ Thanks to all the open source libraries, contributors and donators.
- [AmrDeveloper/CodeView](https://github.com/AmrDeveloper/CodeView) - [AmrDeveloper/CodeView](https://github.com/AmrDeveloper/CodeView)
#### Icon sets #### Icon sets
- [lucide-icons/lucide](https://github.com/lucide-icons/lucide) - [lucide-icons/lucide](https://github.com/lucide-icons/lucide)
- [primer/octicons](https://github.com/primer/octicons) - [primer/octicons](https://github.com/primer/octicons)
- [google/material-design-icons](https://github.com/google/material-design-icons) - [google/material-design-icons](https://github.com/google/material-design-icons)

View File

@ -8,9 +8,7 @@ import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
/** /**
* @author qwerty287 * @author qwerty287
@ -109,5 +107,6 @@ public class AppUtilTest {
assertEquals("https://gitnex.com", AppUtil.changeScheme(Uri.parse("http://gitnex.com"), "https").toString()); assertEquals("https://gitnex.com", AppUtil.changeScheme(Uri.parse("http://gitnex.com"), "https").toString());
assertEquals("ssh://codeberg.org/gitnex/GitNex", AppUtil.changeScheme(Uri.parse("http://codeberg.org/gitnex/GitNex"), "ssh").toString()); assertEquals("ssh://codeberg.org/gitnex/GitNex", AppUtil.changeScheme(Uri.parse("http://codeberg.org/gitnex/GitNex"), "ssh").toString());
} }
} }

View File

@ -88,8 +88,8 @@
<activity <activity
android:name=".activities.MainActivity" android:name=".activities.MainActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:theme="@android:style/Theme.NoTitleBar" android:exported="true"
android:exported="true"> android:theme="@android:style/Theme.NoTitleBar">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
@ -166,9 +166,10 @@
android:name=".activities.WikiActivity" android:name=".activities.WikiActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"/>
<activity <activity
android:windowSoftInputMode="adjustResize"
android:name=".activities.CodeEditorActivity" android:name=".activities.CodeEditorActivity"
android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation" /> android:configChanges="orientation|screenSize|smallestScreenSize|density|screenLayout|keyboard|keyboardHidden|navigation"
android:windowSoftInputMode="adjustResize"/>
<meta-data <meta-data
android:name="com.samsung.android.keepalive.density" android:name="com.samsung.android.keepalive.density"
android:value="true"/> <!-- Version >= 3.0. DeX Dual Mode support --> android:value="true"/> <!-- Version >= 3.0. DeX Dual Mode support -->
@ -177,10 +178,10 @@
android:value="true"/> <!-- deep links --> android:value="true"/> <!-- deep links -->
<activity <activity
android:name=".activities.DeepLinksActivity" android:name=".activities.DeepLinksActivity"
android:exported="true"
android:launchMode="singleTask" android:launchMode="singleTask"
android:noHistory="true" android:noHistory="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar" android:theme="@android:style/Theme.Translucent.NoTitleBar">
android:exported="true">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW"/> <action android:name="android.intent.action.VIEW"/>

View File

@ -14,11 +14,8 @@ import java.util.concurrent.TimeUnit;
public class ActionResult<R> { public class ActionResult<R> {
public enum Status { SUCCESS, FAILED }
private final BlockingQueue<Boolean> blockingQueue; private final BlockingQueue<Boolean> blockingQueue;
private final List<OnFinishedListener<R>> onFinishedListeners; private final List<OnFinishedListener<R>> onFinishedListeners;
private boolean invalidated = false; private boolean invalidated = false;
public ActionResult() { public ActionResult() {
@ -42,13 +39,17 @@ public class ActionResult<R> {
onFinishedListener.onFinished(status, result); onFinishedListener.onFinished(status, result);
} }
} catch (InterruptedException ignored) {} }
catch(InterruptedException ignored) {
}
} }
public void invalidate() { public void invalidate() {
if(invalidated) throw new IllegalStateException("Already invalidated"); if(invalidated) {
throw new IllegalStateException("Already invalidated");
}
this.invalidated = true; this.invalidated = true;
} }
@ -70,11 +71,16 @@ public class ActionResult<R> {
} }
public static class None {} public enum Status {SUCCESS, FAILED}
public interface OnFinishedListener<R> { public interface OnFinishedListener<R> {
void onFinished(Status status, R result); void onFinished(Status status, R result);
}
public static class None {
} }
} }

View File

@ -24,9 +24,7 @@ public class AssigneesActions {
public static void getCurrentIssueAssignees(Context ctx, String repoOwner, String repoName, int issueIndex, List<String> currentAssignees) { public static void getCurrentIssueAssignees(Context ctx, String repoOwner, String repoName, int issueIndex, List<String> currentAssignees) {
Call<Issue> callSingleIssueLabels = RetrofitClient Call<Issue> callSingleIssueLabels = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
callSingleIssueLabels.enqueue(new Callback<>() { callSingleIssueLabels.enqueue(new Callback<>() {
@ -63,11 +61,10 @@ public class AssigneesActions {
}); });
} }
public static void getRepositoryAssignees(Context ctx, String repoOwner, String repoName, List<User> assigneesList, MaterialAlertDialogBuilder materialAlertDialogBuilder, AssigneesListAdapter assigneesAdapter, CustomAssigneesSelectionDialogBinding assigneesBinding, ProgressBar progressBar) { public static void getRepositoryAssignees(Context ctx, String repoOwner, String repoName, List<User> assigneesList, MaterialAlertDialogBuilder materialAlertDialogBuilder, AssigneesListAdapter assigneesAdapter,
CustomAssigneesSelectionDialogBinding assigneesBinding, ProgressBar progressBar) {
Call<List<User>> call = RetrofitClient Call<List<User>> call = RetrofitClient.getApiInterface(ctx).repoGetAssignees(repoOwner, repoName);
.getApiInterface(ctx)
.repoGetAssignees(repoOwner, repoName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -113,4 +110,5 @@ public class AssigneesActions {
} }
}); });
} }
} }

View File

@ -21,9 +21,7 @@ public class CollaboratorActions {
public static void deleteCollaborator(final Context context, String userName, RepositoryContext repository) { public static void deleteCollaborator(final Context context, String userName, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoDeleteCollaborator(repository.getOwner(), repository.getName(), userName);
.getApiInterface(context)
.repoDeleteCollaborator(repository.getOwner(), repository.getName(), userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -70,9 +68,7 @@ public class CollaboratorActions {
AddCollaboratorOption permissionString = new AddCollaboratorOption(); AddCollaboratorOption permissionString = new AddCollaboratorOption();
permissionString.setPermission(permission); permissionString.setPermission(permission);
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoAddCollaborator(repository.getOwner(), repository.getName(), userName, permissionString);
.getApiInterface(context)
.repoAddCollaborator(repository.getOwner(), repository.getName(), userName, permissionString);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -112,4 +108,5 @@ public class CollaboratorActions {
} }
}); });
} }
} }

View File

@ -3,11 +3,7 @@ package org.mian.gitnex.actions;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.Comment; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateIssueCommentOption;
import org.gitnex.tea4j.v2.models.EditIssueCommentOption;
import org.gitnex.tea4j.v2.models.EditIssueOption;
import org.gitnex.tea4j.v2.models.Issue;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.BaseActivity; import org.mian.gitnex.activities.BaseActivity;
import org.mian.gitnex.activities.IssueDetailActivity; import org.mian.gitnex.activities.IssueDetailActivity;
@ -35,10 +31,7 @@ public class IssueActions {
EditIssueCommentOption commentObj = new EditIssueCommentOption(); EditIssueCommentOption commentObj = new EditIssueCommentOption();
commentObj.setBody(comment); commentObj.setBody(comment);
Call<Comment> call = RetrofitClient Call<Comment> call = RetrofitClient.getApiInterface(context).issueEditComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId, commentObj);
.getApiInterface(context)
.issueEditComment(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) commentId, commentObj);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -77,10 +70,7 @@ public class IssueActions {
EditIssueOption issueStatJson = new EditIssueOption(); EditIssueOption issueStatJson = new EditIssueOption();
issueStatJson.setState(issueState); issueStatJson.setState(issueState);
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueEditIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), issueStatJson);
.getApiInterface(ctx)
.issueEditIssue(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), issueStatJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -113,8 +103,7 @@ public class IssueActions {
IssueDetailActivity.singleIssueUpdate = true; IssueDetailActivity.singleIssueUpdate = true;
((IssueDetailActivity) ctx).onResume(); ((IssueDetailActivity) ctx).onResume();
if(((Activity) ctx).getIntent().getStringExtra("openedFromLink") == null || if(((Activity) ctx).getIntent().getStringExtra("openedFromLink") == null || !((Activity) ctx).getIntent().getStringExtra("openedFromLink").equals("true")) {
!((Activity) ctx).getIntent().getStringExtra("openedFromLink").equals("true")) {
RepoDetailActivity.updateRepo = true; RepoDetailActivity.updateRepo = true;
} }
} }
@ -150,10 +139,8 @@ public class IssueActions {
Call<Void> call; Call<Void> call;
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx)
.getApiInterface(ctx) .issueAddSubscription(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
.issueAddSubscription(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -193,8 +180,8 @@ public class IssueActions {
Call<Void> call; Call<Void> call;
call = RetrofitClient.getApiInterface(ctx).issueDeleteSubscription(issue.getRepository().getOwner(), call = RetrofitClient.getApiInterface(ctx)
issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName()); .issueDeleteSubscription(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), ((BaseActivity) ctx).getAccount().getAccount().getUserName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -237,10 +224,7 @@ public class IssueActions {
CreateIssueCommentOption issueComment = new CreateIssueCommentOption(); CreateIssueCommentOption issueComment = new CreateIssueCommentOption();
issueComment.setBody(comment); issueComment.setBody(comment);
Call<Comment> call = RetrofitClient Call<Comment> call = RetrofitClient.getApiInterface(context).issueCreateComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) issue.getIssueIndex(), issueComment);
.getApiInterface(context)
.issueCreateComment(issue.getRepository().getOwner(),
issue.getRepository().getName(), (long) issue.getIssueIndex(), issueComment);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -275,4 +259,5 @@ public class IssueActions {
return actionResult; return actionResult;
} }
} }

View File

@ -23,9 +23,7 @@ public class LabelsActions {
public static void getCurrentIssueLabels(Context ctx, String repoOwner, String repoName, int issueIndex, List<Integer> currentLabelsIds) { public static void getCurrentIssueLabels(Context ctx, String repoOwner, String repoName, int issueIndex, List<Integer> currentLabelsIds) {
Call<List<Label>> callSingleIssueLabels = RetrofitClient Call<List<Label>> callSingleIssueLabels = RetrofitClient.getApiInterface(ctx).issueGetLabels(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetLabels(repoOwner, repoName, (long) issueIndex);
callSingleIssueLabels.enqueue(new Callback<>() { callSingleIssueLabels.enqueue(new Callback<>() {
@ -59,11 +57,10 @@ public class LabelsActions {
}); });
} }
public static void getRepositoryLabels(Context ctx, String repoOwner, String repoName, List<Label> labelsList, MaterialAlertDialogBuilder materialAlertDialogBuilder, LabelsListAdapter labelsAdapter, CustomLabelsSelectionDialogBinding labelsBinding, ProgressBar progressBar) { public static void getRepositoryLabels(Context ctx, String repoOwner, String repoName, List<Label> labelsList, MaterialAlertDialogBuilder materialAlertDialogBuilder, LabelsListAdapter labelsAdapter,
CustomLabelsSelectionDialogBinding labelsBinding, ProgressBar progressBar) {
Call<List<Label>> call = RetrofitClient Call<List<Label>> call = RetrofitClient.getApiInterface(ctx).issueListLabels(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.issueListLabels(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -80,9 +77,7 @@ public class LabelsActions {
} }
// Load organization labels // Load organization labels
Call<List<Label>> callOrgLabels = RetrofitClient Call<List<Label>> callOrgLabels = RetrofitClient.getApiInterface(ctx).orgListLabels(repoOwner, null, null);
.getApiInterface(ctx)
.orgListLabels(repoOwner, null, null);
callOrgLabels.enqueue(new Callback<>() { callOrgLabels.enqueue(new Callback<>() {
@ -129,4 +124,5 @@ public class LabelsActions {
} }
}); });
} }
} }

View File

@ -32,9 +32,7 @@ public class MilestoneActions {
EditMilestoneOption milestoneStateJson = new EditMilestoneOption(); EditMilestoneOption milestoneStateJson = new EditMilestoneOption();
milestoneStateJson.setState(state); milestoneStateJson.setState(state);
Call<Milestone> call = RetrofitClient Call<Milestone> call = RetrofitClient.getApiInterface(ctx).issueEditMilestone(repository.getOwner(), repository.getName(), String.valueOf(milestoneId_), milestoneStateJson);
.getApiInterface(ctx)
.issueEditMilestone(repository.getOwner(), repository.getName(), String.valueOf(milestoneId_), milestoneStateJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {

View File

@ -17,9 +17,7 @@ import retrofit2.Response;
public class PullRequestActions { public class PullRequestActions {
public static void deleteHeadBranch(Context context, String repoOwner, String repoName, String headBranch, boolean showToasts) { public static void deleteHeadBranch(Context context, String repoOwner, String repoName, String headBranch, boolean showToasts) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoDeleteBranch(repoOwner, repoName, headBranch);
.getApiInterface(context)
.repoDeleteBranch(repoOwner, repoName, headBranch);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -79,8 +77,7 @@ public class PullRequestActions {
else { else {
strategy = "rebase"; strategy = "rebase";
} }
RetrofitClient.getApiInterface(context).repoUpdatePullRequest(repoOwner, repoName, Long.valueOf(index), strategy) RetrofitClient.getApiInterface(context).repoUpdatePullRequest(repoOwner, repoName, Long.valueOf(index), strategy).enqueue(new Callback<>() {
.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call call, @NonNull Response response) { public void onResponse(@NonNull Call call, @NonNull Response response) {
@ -108,4 +105,5 @@ public class PullRequestActions {
} }
}); });
} }
} }

View File

@ -20,9 +20,7 @@ public class RepositoryActions {
public static void starRepository(final Context context, RepositoryContext repository) { public static void starRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentPutStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentPutStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -64,9 +62,7 @@ public class RepositoryActions {
public static void unStarRepository(final Context context, RepositoryContext repository) { public static void unStarRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentDeleteStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentDeleteStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -108,9 +104,7 @@ public class RepositoryActions {
public static void watchRepository(final Context context, RepositoryContext repository) { public static void watchRepository(final Context context, RepositoryContext repository) {
Call<WatchInfo> call = RetrofitClient Call<WatchInfo> call = RetrofitClient.getApiInterface(context).userCurrentPutSubscription(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentPutSubscription(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -153,9 +147,7 @@ public class RepositoryActions {
public static void unWatchRepository(final Context context, RepositoryContext repository) { public static void unWatchRepository(final Context context, RepositoryContext repository) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).userCurrentDeleteStar(repository.getOwner(), repository.getName());
.getApiInterface(context)
.userCurrentDeleteStar(repository.getOwner(), repository.getName());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -191,4 +183,5 @@ public class RepositoryActions {
} }
}); });
} }
} }

View File

@ -20,9 +20,7 @@ public class TeamActions {
public static void removeTeamMember(final Context context, String userName, int teamId) { public static void removeTeamMember(final Context context, String userName, int teamId) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgRemoveTeamMember((long) teamId, userName);
.getApiInterface(context)
.orgRemoveTeamMember((long) teamId, userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -66,9 +64,7 @@ public class TeamActions {
public static void addTeamMember(final Context context, String userName, int teamId) { public static void addTeamMember(final Context context, String userName, int teamId) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgAddTeamMember((long) teamId, userName);
.getApiInterface(context)
.orgAddTeamMember((long) teamId, userName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -111,9 +107,7 @@ public class TeamActions {
public static void removeTeamRepo(final Context context, String orgName, int teamId, String repo) { public static void removeTeamRepo(final Context context, String orgName, int teamId, String repo) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgRemoveTeamRepository((long) teamId, orgName, repo);
.getApiInterface(context)
.orgRemoveTeamRepository((long) teamId, orgName, repo);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -158,9 +152,7 @@ public class TeamActions {
public static void addTeamRepo(final Context context, String orgName, int teamId, String repo) { public static void addTeamRepo(final Context context, String orgName, int teamId, String repo) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).orgAddTeamRepository((long) teamId, orgName, repo);
.getApiInterface(context)
.orgAddTeamRepository((long) teamId, orgName, repo);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,4 +193,5 @@ public class TeamActions {
} }
}); });
} }
} }

View File

@ -68,9 +68,7 @@ public class AddCollaboratorToRepositoryActivity extends BaseActivity {
public void loadUserSearchList(String searchKeyword) { public void loadUserSearchList(String searchKeyword) {
Call<InlineResponse2001> call = RetrofitClient Call<InlineResponse2001> call = RetrofitClient.getApiInterface(ctx).userSearch(searchKeyword, null, 1, 10);
.getApiInterface(ctx)
.userSearch(searchKeyword, null, 1, 10);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -103,8 +101,7 @@ public class AddCollaboratorToRepositoryActivity extends BaseActivity {
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setHasFixedSize(true); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setHasFixedSize(true);
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setLayoutManager(new LinearLayoutManager(ctx)); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.addItemDecoration(dividerItemDecoration); activityAddCollaboratorToRepositoryBinding.recyclerViewUserSearch.addItemDecoration(dividerItemDecoration);
activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE); activityAddCollaboratorToRepositoryBinding.progressBar.setVisibility(View.VISIBLE);
@ -131,4 +128,5 @@ public class AddCollaboratorToRepositoryActivity extends BaseActivity {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -17,11 +17,7 @@ import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityAddNewAccountBinding; import org.mian.gitnex.databinding.ActivityAddNewAccountBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.PathsHelper;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.UrlHelper;
import org.mian.gitnex.helpers.Version;
import org.mian.gitnex.structs.Protocol; import org.mian.gitnex.structs.Protocol;
import java.net.URI; import java.net.URI;
import java.util.Objects; import java.util.Objects;
@ -61,7 +57,8 @@ public class AddNewAccountActivity extends BaseActivity {
if(scheme != null && scheme.equals("http")) { if(scheme != null && scheme.equals("http")) {
viewBinding.protocolSpinner.setText(Protocol.HTTP.toString()); viewBinding.protocolSpinner.setText(Protocol.HTTP.toString());
spinnerSelectedValue = Protocol.HTTP.toString(); spinnerSelectedValue = Protocol.HTTP.toString();
} else { // default is https }
else { // default is https
viewBinding.protocolSpinner.setText(Protocol.HTTPS.toString()); viewBinding.protocolSpinner.setText(Protocol.HTTPS.toString());
spinnerSelectedValue = Protocol.HTTPS.toString(); spinnerSelectedValue = Protocol.HTTPS.toString();
} }
@ -114,8 +111,7 @@ public class AddNewAccountActivity extends BaseActivity {
URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET, "http")).toUri(); URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET, "http")).toUri();
URI instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(protocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")) URI instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(protocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")).toUri();
.toUri();
versionCheck(instanceUrl.toString(), loginToken); versionCheck(instanceUrl.toString(), loginToken);
serverPageLimitSettings(); serverPageLimitSettings();
@ -152,10 +148,8 @@ public class AddNewAccountActivity extends BaseActivity {
if(giteaVersion.less(getString(R.string.versionLow))) { if(giteaVersion.less(getString(R.string.versionLow))) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(getString(R.string.versionAlertDialogHeader))
.setTitle(getString(R.string.versionAlertDialogHeader)) .setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion())).setNeutralButton(getString(R.string.cancelButton), null)
.setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion()))
.setNeutralButton(getString(R.string.cancelButton), null)
.setPositiveButton(getString(R.string.textContinue), (dialog, which) -> { .setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
@ -290,4 +284,5 @@ public class AddNewAccountActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -105,4 +105,5 @@ public class AddNewTeamRepoActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -20,13 +20,11 @@ import org.mian.gitnex.viewmodels.AdminCronTasksViewModel;
public class AdminCronTasksActivity extends BaseActivity { public class AdminCronTasksActivity extends BaseActivity {
private final int PAGE = 1;
private AdminCronTasksViewModel adminCronTasksViewModel; private AdminCronTasksViewModel adminCronTasksViewModel;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private AdminCronTasksAdapter adapter; private AdminCronTasksAdapter adapter;
private ActivityAdminCronTasksBinding activityAdminCronTasksBinding; private ActivityAdminCronTasksBinding activityAdminCronTasksBinding;
private final int PAGE = 1;
private int resultLimit; private int resultLimit;
@Override @Override
@ -48,8 +46,7 @@ public class AdminCronTasksActivity extends BaseActivity {
activityAdminCronTasksBinding.recyclerView.setHasFixedSize(true); activityAdminCronTasksBinding.recyclerView.setHasFixedSize(true);
activityAdminCronTasksBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); activityAdminCronTasksBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminCronTasksBinding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminCronTasksBinding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
activityAdminCronTasksBinding.recyclerView.addItemDecoration(dividerItemDecoration); activityAdminCronTasksBinding.recyclerView.addItemDecoration(dividerItemDecoration);
activityAdminCronTasksBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { activityAdminCronTasksBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -83,4 +80,5 @@ public class AdminCronTasksActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -55,8 +55,7 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
activityAdminGetUsersBinding.recyclerView.setHasFixedSize(true); activityAdminGetUsersBinding.recyclerView.setHasFixedSize(true);
activityAdminGetUsersBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); activityAdminGetUsersBinding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminGetUsersBinding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(activityAdminGetUsersBinding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
activityAdminGetUsersBinding.recyclerView.addItemDecoration(dividerItemDecoration); activityAdminGetUsersBinding.recyclerView.addItemDecoration(dividerItemDecoration);
activityAdminGetUsersBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { activityAdminGetUsersBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -68,7 +67,7 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
}, 50)); }, 50));
fetchDataAsync(); fetchDataAsync();
}; }
private void fetchDataAsync() { private void fetchDataAsync() {
@ -134,7 +133,9 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() { searchView.setOnQueryTextListener(new androidx.appcompat.widget.SearchView.OnQueryTextListener() {
@Override @Override
public boolean onQueryTextSubmit(String query) { return true; } public boolean onQueryTextSubmit(String query) {
return true;
}
@Override @Override
public boolean onQueryTextChange(String newText) { public boolean onQueryTextChange(String newText) {
@ -182,4 +183,5 @@ public class AdminGetUsersActivity extends BaseActivity implements BottomSheetLi
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -55,8 +55,7 @@ public class AdminUnadoptedReposActivity extends BaseActivity {
binding.recyclerView.setHasFixedSize(true); binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx)); binding.recyclerView.setLayoutManager(new LinearLayoutManager(ctx));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(binding.recyclerView.getContext(), DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(binding.recyclerView.getContext(), DividerItemDecoration.VERTICAL);
DividerItemDecoration.VERTICAL);
binding.recyclerView.addItemDecoration(dividerItemDecoration); binding.recyclerView.addItemDecoration(dividerItemDecoration);
binding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { binding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -112,4 +111,5 @@ public class AdminUnadoptedReposActivity extends BaseActivity {
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -45,12 +45,7 @@ public abstract class BaseActivity extends AppCompatActivity {
break; break;
case 2: case 2:
if(TimeHelper.timeBetweenHours( if(TimeHelper.timeBetweenHours(tinyDB.getInt("darkThemeTimeHour", 18), tinyDB.getInt("lightThemeTimeHour", 6), tinyDB.getInt("darkThemeTimeMinute", 0), tinyDB.getInt("lightThemeTimeMinute", 0))) {
tinyDB.getInt("darkThemeTimeHour", 18),
tinyDB.getInt("lightThemeTimeHour", 6),
tinyDB.getInt("darkThemeTimeMinute", 0),
tinyDB.getInt("lightThemeTimeMinute", 0))
) {
setTheme(R.style.AppTheme); setTheme(R.style.AppTheme);
} }
@ -64,12 +59,7 @@ public abstract class BaseActivity extends AppCompatActivity {
setTheme(R.style.AppThemeRetro); setTheme(R.style.AppThemeRetro);
break; break;
case 4: case 4:
if(TimeHelper.timeBetweenHours( if(TimeHelper.timeBetweenHours(tinyDB.getInt("darkThemeTimeHour", 18), tinyDB.getInt("lightThemeTimeHour", 6), tinyDB.getInt("darkThemeTimeMinute", 0), tinyDB.getInt("lightThemeTimeMinute", 0))) {
tinyDB.getInt("darkThemeTimeHour", 18),
tinyDB.getInt("lightThemeTimeHour", 6),
tinyDB.getInt("darkThemeTimeMinute", 0),
tinyDB.getInt("lightThemeTimeMinute", 0))
) {
setTheme(R.style.AppTheme); setTheme(R.style.AppTheme);
} }
@ -127,15 +117,14 @@ public abstract class BaseActivity extends AppCompatActivity {
} }
// Authentication failed, close the app // Authentication failed, close the app
@Override public void onAuthenticationFailed() { @Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed(); super.onAuthenticationFailed();
} }
}); });
BiometricPrompt.PromptInfo biometricPromptBuilder = new BiometricPrompt.PromptInfo.Builder() BiometricPrompt.PromptInfo biometricPromptBuilder = new BiometricPrompt.PromptInfo.Builder().setTitle(getString(R.string.biometricAuthTitle)).setSubtitle(getString(R.string.biometricAuthSubTitle))
.setTitle(getString(R.string.biometricAuthTitle))
.setSubtitle(getString(R.string.biometricAuthSubTitle))
.setNegativeButtonText(getString(R.string.cancelButton)).build(); .setNegativeButtonText(getString(R.string.cancelButton)).build();
biometricPrompt.authenticate(biometricPromptBuilder); biometricPrompt.authenticate(biometricPromptBuilder);
@ -146,6 +135,7 @@ public abstract class BaseActivity extends AppCompatActivity {
public AccountContext getAccount() { public AccountContext getAccount() {
return ((MainApplication) getApplication()).currentAccount; return ((MainApplication) getApplication()).currentAccount;
} }
} }

View File

@ -10,11 +10,7 @@ import com.amrdeveloper.codeview.Code;
import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.EnumUtils;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.databinding.ActivityCodeEditorBinding; import org.mian.gitnex.databinding.ActivityCodeEditorBinding;
import org.mian.gitnex.helpers.codeeditor.CustomCodeViewAdapter; import org.mian.gitnex.helpers.codeeditor.*;
import org.mian.gitnex.helpers.codeeditor.LanguageManager;
import org.mian.gitnex.helpers.codeeditor.LanguageName;
import org.mian.gitnex.helpers.codeeditor.SourcePositionListener;
import org.mian.gitnex.helpers.codeeditor.ThemeName;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -26,10 +22,10 @@ import java.util.Map;
public class CodeEditorActivity extends BaseActivity { public class CodeEditorActivity extends BaseActivity {
private final ThemeName currentTheme = ThemeName.FIVE_COLOR;
private ActivityCodeEditorBinding binding; private ActivityCodeEditorBinding binding;
private LanguageManager languageManager; private LanguageManager languageManager;
private LanguageName currentLanguage = LanguageName.UNKNOWN; private LanguageName currentLanguage = LanguageName.UNKNOWN;
private final ThemeName currentTheme = ThemeName.FIVE_COLOR;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -146,4 +142,5 @@ public class CodeEditorActivity extends BaseActivity {
binding.sourcePosition.setText(getString(R.string.sourcePosition, line, column)); binding.sourcePosition.setText(getString(R.string.sourcePosition, line, column));
}); });
} }
} }

View File

@ -29,20 +29,15 @@ public class CommitDetailActivity extends BaseActivity {
@Override @Override
public void handleOnBackPressed() { public void handleOnBackPressed() {
if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) { if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) {
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction() }
.replace(R.id.fragment_container, fragment) else {
.commit();
} else {
finish(); finish();
} }
} }
}); });
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
} }

View File

@ -38,17 +38,16 @@ import retrofit2.Response;
public class CommitsActivity extends BaseActivity { public class CommitsActivity extends BaseActivity {
private final String TAG = "CommitsActivity";
public RepositoryContext repository;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private TextView noData; private TextView noData;
private ProgressBar progressBar; private ProgressBar progressBar;
private final String TAG = "CommitsActivity";
private int resultLimit; private int resultLimit;
private int pageSize = 1; private int pageSize = 1;
private RecyclerView recyclerView; private RecyclerView recyclerView;
private List<Commit> commitsList; private List<Commit> commitsList;
private CommitsAdapter adapter; private CommitsAdapter adapter;
public RepositoryContext repository;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {

View File

@ -15,12 +15,7 @@ import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts; import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateFileOptions;
import org.gitnex.tea4j.v2.models.DeleteFileOptions;
import org.gitnex.tea4j.v2.models.FileDeleteResponse;
import org.gitnex.tea4j.v2.models.FileResponse;
import org.gitnex.tea4j.v2.models.UpdateFileOptions;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityCreateFileBinding; import org.mian.gitnex.databinding.ActivityCreateFileBinding;
@ -41,19 +36,21 @@ import retrofit2.Callback;
public class CreateFileActivity extends BaseActivity { public class CreateFileActivity extends BaseActivity {
private ActivityCreateFileBinding binding;
public static final int FILE_ACTION_CREATE = 0; public static final int FILE_ACTION_CREATE = 0;
public static final int FILE_ACTION_DELETE = 1; public static final int FILE_ACTION_DELETE = 1;
public static final int FILE_ACTION_EDIT = 2; public static final int FILE_ACTION_EDIT = 2;
private final List<String> branches = new ArrayList<>();
private ActivityCreateFileBinding binding;
ActivityResultLauncher<Intent> codeEditorActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
assert data != null;
binding.newFileContent.setText(data.getStringExtra("fileContentFromActivity"));
}
});
private int fileAction = FILE_ACTION_CREATE; private int fileAction = FILE_ACTION_CREATE;
private String filePath; private String filePath;
private String fileSha; private String fileSha;
private final List<String> branches = new ArrayList<>();
private RepositoryContext repository; private RepositoryContext repository;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@ -80,8 +77,7 @@ public class CreateFileActivity extends BaseActivity {
touchView.getParent().requestDisallowInterceptTouchEvent(true); touchView.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && if((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 && (motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
(motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
touchView.getParent().requestDisallowInterceptTouchEvent(false); touchView.getParent().requestDisallowInterceptTouchEvent(false);
} }
@ -124,9 +120,8 @@ public class CreateFileActivity extends BaseActivity {
disableProcessButton(); disableProcessButton();
binding.openCodeEditor.setOnClickListener(v -> binding.openCodeEditor.setOnClickListener(
launchCodeEditorActivityForResult(Objects.requireNonNull(binding.newFileContent.getText()).toString(), FilenameUtils.getExtension(String.valueOf(binding.newFileName.getText()))) v -> launchCodeEditorActivityForResult(Objects.requireNonNull(binding.newFileContent.getText()).toString(), FilenameUtils.getExtension(String.valueOf(binding.newFileName.getText()))));
);
NetworkStatusObserver networkStatusObserver = NetworkStatusObserver.getInstance(ctx); NetworkStatusObserver networkStatusObserver = NetworkStatusObserver.getInstance(ctx);
networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> binding.newFileCreate.setEnabled(hasNetworkConnection))); networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> binding.newFileCreate.setEnabled(hasNetworkConnection)));
@ -141,15 +136,6 @@ public class CreateFileActivity extends BaseActivity {
codeEditorActivityResultLauncher.launch(intent); codeEditorActivityResultLauncher.launch(intent);
} }
ActivityResultLauncher<Intent> codeEditorActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
assert data != null;
binding.newFileContent.setText(data.getStringExtra("fileContentFromActivity"));
}
});
private void processNewFile() { private void processNewFile() {
String newFileName = binding.newFileName.getText() != null ? binding.newFileName.getText().toString() : ""; String newFileName = binding.newFileName.getText() != null ? binding.newFileName.getText().toString() : "";
@ -208,9 +194,7 @@ public class CreateFileActivity extends BaseActivity {
createNewFileJsonStr.setNewBranch(branchName); createNewFileJsonStr.setNewBranch(branchName);
} }
Call<FileResponse> call = RetrofitClient Call<FileResponse> call = RetrofitClient.getApiInterface(ctx).repoCreateFile(createNewFileJsonStr, repoOwner, repoName, fileName);
.getApiInterface(ctx)
.repoCreateFile(createNewFileJsonStr, repoOwner, repoName, fileName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -268,9 +252,7 @@ public class CreateFileActivity extends BaseActivity {
deleteFileJsonStr.setNewBranch(branchName); deleteFileJsonStr.setNewBranch(branchName);
} }
Call<FileDeleteResponse> call = RetrofitClient Call<FileDeleteResponse> call = RetrofitClient.getApiInterface(ctx).repoDeleteFileWithBody(repoOwner, repoName, fileName, deleteFileJsonStr);
.getApiInterface(ctx)
.repoDeleteFileWithBody(repoOwner, repoName, fileName, deleteFileJsonStr);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -329,9 +311,7 @@ public class CreateFileActivity extends BaseActivity {
editFileJsonStr.setNewBranch(branchName); editFileJsonStr.setNewBranch(branchName);
} }
Call<FileResponse> call = RetrofitClient Call<FileResponse> call = RetrofitClient.getApiInterface(ctx).repoUpdateFile(editFileJsonStr, repoOwner, repoName, fileName);
.getApiInterface(ctx)
.repoUpdateFile(editFileJsonStr, repoOwner, repoName, fileName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -378,9 +358,7 @@ public class CreateFileActivity extends BaseActivity {
private void getBranches(String repoOwner, String repoName) { private void getBranches(String repoOwner, String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -410,12 +388,18 @@ public class CreateFileActivity extends BaseActivity {
}); });
} }
private void disableProcessButton() { binding.newFileCreate.setEnabled(false); } private void disableProcessButton() {
private void enableProcessButton() { binding.newFileCreate.setEnabled(true); } binding.newFileCreate.setEnabled(false);
}
private void enableProcessButton() {
binding.newFileCreate.setEnabled(true);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -12,11 +12,7 @@ import android.widget.ArrayAdapter;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.CreateIssueOption; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Issue;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.AssigneesActions; import org.mian.gitnex.actions.AssigneesActions;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
@ -32,12 +28,7 @@ import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Constants; import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -47,22 +38,18 @@ import retrofit2.Callback;
public class CreateIssueActivity extends BaseActivity implements View.OnClickListener, LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener { public class CreateIssueActivity extends BaseActivity implements View.OnClickListener, LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener {
private final List<Label> labelsList = new ArrayList<>();
private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private final List<User> assigneesList = new ArrayList<>();
private ActivityCreateIssueBinding viewBinding; private ActivityCreateIssueBinding viewBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private int milestoneId; private int milestoneId;
private Date currentDate = null; private Date currentDate = null;
private RepositoryContext repository; private RepositoryContext repository;
private LabelsListAdapter labelsAdapter; private LabelsListAdapter labelsAdapter;
private AssigneesListAdapter assigneesAdapter; private AssigneesListAdapter assigneesAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder; private MaterialAlertDialogBuilder materialAlertDialogBuilder;
private List<Integer> labelsIds = new ArrayList<>(); private List<Integer> labelsIds = new ArrayList<>();
private final List<Label> labelsList = new ArrayList<>();
private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private final List<User> assigneesList = new ArrayList<>();
private List<String> assigneesListData = new ArrayList<>(); private List<String> assigneesListData = new ArrayList<>();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@ -160,23 +147,20 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate( CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = assigneesBinding.getRoot(); View view = assigneesBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
materialAlertDialogBuilder.setNeutralButton(R.string.close, null); materialAlertDialogBuilder.setNeutralButton(R.string.close, null);
AssigneesActions.getRepositoryAssignees(ctx, repository.getOwner(), repository.getName(), assigneesList, materialAlertDialogBuilder, assigneesAdapter, AssigneesActions.getRepositoryAssignees(ctx, repository.getOwner(), repository.getName(), assigneesList, materialAlertDialogBuilder, assigneesAdapter, assigneesBinding, viewBinding.progressBar);
assigneesBinding, viewBinding.progressBar);
} }
private void showLabels() { private void showLabels() {
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate( CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = labelsBinding.getRoot(); View view = labelsBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -224,9 +208,7 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
createNewIssueJson.setAssignees(assigneesListData); createNewIssueJson.setAssignees(assigneesListData);
createNewIssueJson.setLabels(labelIds); createNewIssueJson.setLabels(labelIds);
Call<Issue> call3 = RetrofitClient Call<Issue> call3 = RetrofitClient.getApiInterface(ctx).issueCreateIssue(repoOwner, repoName, createNewIssueJson);
.getApiInterface(ctx)
.issueCreateIssue(repoOwner, repoName, createNewIssueJson);
call3.enqueue(new Callback<>() { call3.enqueue(new Callback<>() {
@ -273,9 +255,7 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
private void getMilestones(String repoOwner, String repoName, int resultLimit) { private void getMilestones(String repoOwner, String repoName, int resultLimit) {
String msState = "open"; String msState = "open";
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
.getApiInterface(ctx)
.issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -342,8 +322,7 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
viewBinding.newIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); viewBinding.newIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
@ -370,4 +349,5 @@ public class CreateIssueActivity extends BaseActivity implements View.OnClickLis
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -39,7 +39,9 @@ public class CreateLabelActivity extends BaseActivity {
private RepositoryContext repository; private RepositoryContext repository;
private String labelColor = ""; private String labelColor = "";
private final View.OnClickListener createLabelListener = v -> processCreateLabel();
private String labelColorDefault = ""; private String labelColorDefault = "";
private final View.OnClickListener updateLabelListener = v -> processUpdateLabel();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -105,10 +107,6 @@ public class CreateLabelActivity extends BaseActivity {
} }
} }
private final View.OnClickListener createLabelListener = v -> processCreateLabel();
private final View.OnClickListener updateLabelListener = v -> processUpdateLabel();
private void processUpdateLabel() { private void processUpdateLabel() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -144,8 +142,7 @@ public class CreateLabelActivity extends BaseActivity {
} }
disableProcessButton(); disableProcessButton();
patchLabel(repository, updateLabelName, updateLabelColor, Integer.parseInt( patchLabel(repository, updateLabelName, updateLabelColor, Integer.parseInt(Objects.requireNonNull(getIntent().getStringExtra("labelId"))));
Objects.requireNonNull(getIntent().getStringExtra("labelId"))));
} }
private void processCreateLabel() { private void processCreateLabel() {
@ -201,7 +198,8 @@ public class CreateLabelActivity extends BaseActivity {
else if(repository != null) { else if(repository != null) {
call = RetrofitClient.getApiInterface(ctx).issueCreateLabel(repository.getOwner(), repository.getName(), createLabelFunc); call = RetrofitClient.getApiInterface(ctx).issueCreateLabel(repository.getOwner(), repository.getName(), createLabelFunc);
} else { }
else {
return; return;
} }
@ -361,7 +359,9 @@ public class CreateLabelActivity extends BaseActivity {
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if(repository == null) return; if(repository == null) {
return;
}
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }

View File

@ -41,6 +41,7 @@ public class CreateMilestoneActivity extends BaseActivity implements View.OnClic
private RepositoryContext repository; private RepositoryContext repository;
private Date currentDate = null; private Date currentDate = null;
private final View.OnClickListener createMilestoneListener = v -> processNewMilestone();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -92,8 +93,6 @@ public class CreateMilestoneActivity extends BaseActivity implements View.OnClic
} }
private final View.OnClickListener createMilestoneListener = v -> processNewMilestone();
private void processNewMilestone() { private void processNewMilestone() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -135,9 +134,7 @@ public class CreateMilestoneActivity extends BaseActivity implements View.OnClic
Call<Milestone> call; Call<Milestone> call;
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).issueCreateMilestone(repoOwner, repoName, createMilestone);
.getApiInterface(ctx)
.issueCreateMilestone(repoOwner, repoName, createMilestone);
call.enqueue(new Callback<Milestone>() { call.enqueue(new Callback<Milestone>() {
@ -188,8 +185,7 @@ public class CreateMilestoneActivity extends BaseActivity implements View.OnClic
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
milestoneDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); milestoneDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);

View File

@ -33,6 +33,7 @@ public class CreateNewUserActivity extends BaseActivity {
private EditText userEmail; private EditText userEmail;
private EditText userPassword; private EditText userPassword;
private Button createUserButton; private Button createUserButton;
private final View.OnClickListener createNewUserListener = v -> processCreateNewUser();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -122,9 +123,7 @@ public class CreateNewUserActivity extends BaseActivity {
createUser.setPassword(newUserPassword); createUser.setPassword(newUserPassword);
createUser.setMustChangePassword(true); createUser.setMustChangePassword(true);
Call<User> call = RetrofitClient Call<User> call = RetrofitClient.getApiInterface(ctx).adminCreateUser(createUser);
.getApiInterface(ctx)
.adminCreateUser(createUser);
call.enqueue(new Callback<User>() { call.enqueue(new Callback<User>() {
@ -174,8 +173,6 @@ public class CreateNewUserActivity extends BaseActivity {
} }
private final View.OnClickListener createNewUserListener = v -> processCreateNewUser();
private void initCloseListener() { private void initCloseListener() {
onClickListener = view -> finish(); onClickListener = view -> finish();

View File

@ -35,6 +35,7 @@ public class CreateOrganizationActivity extends BaseActivity {
private EditText orgName; private EditText orgName;
private EditText orgDesc; private EditText orgDesc;
private final View.OnClickListener createOrgListener = v -> processNewOrganization();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -89,8 +90,6 @@ public class CreateOrganizationActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private final View.OnClickListener createOrgListener = v -> processNewOrganization();
private void processNewOrganization() { private void processNewOrganization() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -135,9 +134,7 @@ public class CreateOrganizationActivity extends BaseActivity {
createOrganization.setDescription(orgDesc); createOrganization.setDescription(orgDesc);
createOrganization.setUsername(orgName); createOrganization.setUsername(orgName);
Call<Organization> call = RetrofitClient Call<Organization> call = RetrofitClient.getApiInterface(ctx).orgCreate(createOrganization);
.getApiInterface(ctx)
.orgCreate(createOrganization);
call.enqueue(new Callback<Organization>() { call.enqueue(new Callback<Organization>() {

View File

@ -11,11 +11,7 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreatePullRequestOption;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
import org.mian.gitnex.adapters.LabelsListAdapter; import org.mian.gitnex.adapters.LabelsListAdapter;
@ -26,12 +22,7 @@ import org.mian.gitnex.fragments.PullRequestsFragment;
import org.mian.gitnex.helpers.Constants; import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -41,21 +32,18 @@ import retrofit2.Callback;
public class CreatePullRequestActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener { public class CreatePullRequestActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener {
private View.OnClickListener onClickListener;
private ActivityCreatePrBinding viewBinding;
private List<Integer> labelsIds = new ArrayList<>();
private final List<String> assignees = new ArrayList<>(); private final List<String> assignees = new ArrayList<>();
private int milestoneId;
private Date currentDate = null;
private RepositoryContext repository;
private LabelsListAdapter labelsAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>(); LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
List<String> branchesList = new ArrayList<>(); List<String> branchesList = new ArrayList<>();
List<Label> labelsList = new ArrayList<>(); List<Label> labelsList = new ArrayList<>();
private View.OnClickListener onClickListener;
private ActivityCreatePrBinding viewBinding;
private List<Integer> labelsIds = new ArrayList<>();
private int milestoneId;
private Date currentDate = null;
private RepositoryContext repository;
private LabelsListAdapter labelsAdapter;
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -90,9 +78,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
initCloseListener(); initCloseListener();
closeActivity.setOnClickListener(onClickListener); closeActivity.setOnClickListener(onClickListener);
viewBinding.prDueDate.setOnClickListener(dueDate -> viewBinding.prDueDate.setOnClickListener(dueDate -> setDueDate());
setDueDate()
);
disableProcessButton(); disableProcessButton();
@ -163,9 +149,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
createPullRequest.setLabels(labelIds); createPullRequest.setLabels(labelIds);
createPullRequest.setDueDate(currentDate); createPullRequest.setDueDate(currentDate);
Call<PullRequest> transferCall = RetrofitClient Call<PullRequest> transferCall = RetrofitClient.getApiInterface(ctx).repoCreatePullRequest(repository.getOwner(), repository.getName(), createPullRequest);
.getApiInterface(ctx)
.repoCreatePullRequest(repository.getOwner(), repository.getName(), createPullRequest);
transferCall.enqueue(new Callback<>() { transferCall.enqueue(new Callback<>() {
@ -224,8 +208,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void showLabels() { private void showLabels() {
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate( CustomLabelsSelectionDialogBinding labelsBinding = CustomLabelsSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = labelsBinding.getRoot(); View view = labelsBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -235,9 +218,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void getBranches(String repoOwner, String repoName) { private void getBranches(String repoOwner, String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -277,9 +258,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
private void getMilestones(String repoOwner, String repoName, int resultLimit) { private void getMilestones(String repoOwner, String repoName, int resultLimit) {
String msState = "open"; String msState = "open";
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
.getApiInterface(ctx)
.issueGetMilestonesList(repoOwner, repoName, msState, null, 1, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -336,8 +315,7 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
viewBinding.prDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); viewBinding.prDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
@ -364,4 +342,5 @@ public class CreatePullRequestActivity extends BaseActivity implements LabelsLis
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -8,18 +8,9 @@ import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateReleaseOption;
import org.gitnex.tea4j.v2.models.CreateTagOption;
import org.gitnex.tea4j.v2.models.Release;
import org.gitnex.tea4j.v2.models.Tag;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityCreateReleaseBinding; import org.mian.gitnex.databinding.ActivityCreateReleaseBinding;
@ -38,8 +29,9 @@ import retrofit2.Callback;
public class CreateReleaseActivity extends BaseActivity { public class CreateReleaseActivity extends BaseActivity {
private View.OnClickListener onClickListener;
public ImageView closeActivity; public ImageView closeActivity;
List<String> branchesList = new ArrayList<>();
private View.OnClickListener onClickListener;
private EditText releaseTagName; private EditText releaseTagName;
private AutoCompleteTextView releaseBranch; private AutoCompleteTextView releaseBranch;
private EditText releaseTitle; private EditText releaseTitle;
@ -49,10 +41,8 @@ public class CreateReleaseActivity extends BaseActivity {
private Button createNewRelease; private Button createNewRelease;
private String selectedBranch; private String selectedBranch;
private Button createNewTag; private Button createNewTag;
private RepositoryContext repository; private RepositoryContext repository;
private final View.OnClickListener createReleaseListener = v -> processNewRelease();
List<String> branchesList = new ArrayList<>();
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@Override @Override
@ -141,9 +131,7 @@ public class CreateReleaseActivity extends BaseActivity {
createReleaseJson.setTagName(tagName); createReleaseJson.setTagName(tagName);
createReleaseJson.setTarget(selectedBranch); createReleaseJson.setTarget(selectedBranch);
Call<Tag> call = RetrofitClient Call<Tag> call = RetrofitClient.getApiInterface(ctx).repoCreateTag(repository.getOwner(), repository.getName(), createReleaseJson);
.getApiInterface(ctx)
.repoCreateTag(repository.getOwner(), repository.getName(), createReleaseJson);
call.enqueue(new Callback<Tag>() { call.enqueue(new Callback<Tag>() {
@ -184,8 +172,6 @@ public class CreateReleaseActivity extends BaseActivity {
}); });
} }
private final View.OnClickListener createReleaseListener = v -> processNewRelease();
private void processNewRelease() { private void processNewRelease() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -225,8 +211,8 @@ public class CreateReleaseActivity extends BaseActivity {
createNewReleaseFunc(repository.getOwner(), repository.getName(), newReleaseTagName, newReleaseTitle, newReleaseContent, selectedBranch, newReleaseType, newReleaseDraft); createNewReleaseFunc(repository.getOwner(), repository.getName(), newReleaseTagName, newReleaseTitle, newReleaseContent, selectedBranch, newReleaseType, newReleaseDraft);
} }
private void createNewReleaseFunc(String repoOwner, String repoName, String newReleaseTagName, String newReleaseTitle, String newReleaseContent, private void createNewReleaseFunc(String repoOwner, String repoName, String newReleaseTagName, String newReleaseTitle, String newReleaseContent, String selectedBranch, boolean newReleaseType,
String selectedBranch, boolean newReleaseType, boolean newReleaseDraft) { boolean newReleaseDraft) {
CreateReleaseOption createReleaseJson = new CreateReleaseOption(); CreateReleaseOption createReleaseJson = new CreateReleaseOption();
createReleaseJson.setName(newReleaseTitle); createReleaseJson.setName(newReleaseTitle);
@ -236,9 +222,7 @@ public class CreateReleaseActivity extends BaseActivity {
createReleaseJson.setPrerelease(newReleaseType); createReleaseJson.setPrerelease(newReleaseType);
createReleaseJson.setTargetCommitish(selectedBranch); createReleaseJson.setTargetCommitish(selectedBranch);
Call<Release> call = RetrofitClient Call<Release> call = RetrofitClient.getApiInterface(ctx).repoCreateRelease(repoOwner, repoName, createReleaseJson);
.getApiInterface(ctx)
.repoCreateRelease(repoOwner, repoName, createReleaseJson);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -285,9 +269,7 @@ public class CreateReleaseActivity extends BaseActivity {
private void getBranches(final String repoOwner, final String repoName) { private void getBranches(final String repoOwner, final String repoName) {
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repoOwner, repoName, null, null);
.getApiInterface(ctx)
.repoListBranches(repoOwner, repoName, null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -347,4 +329,5 @@ public class CreateReleaseActivity extends BaseActivity {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -7,12 +7,7 @@ import android.os.Looper;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.CreateRepoOption; import org.gitnex.tea4j.v2.models.CreateRepoOption;
import org.gitnex.tea4j.v2.models.Organization; import org.gitnex.tea4j.v2.models.Organization;
@ -36,23 +31,20 @@ import retrofit2.Callback;
public class CreateRepoActivity extends BaseActivity { public class CreateRepoActivity extends BaseActivity {
//https://github.com/go-gitea/gitea/blob/52cfd2743c0e85b36081cf80a850e6a5901f1865/models/repo.go#L964-L967
final List<String> reservedRepoNames = Arrays.asList(".", "..");
final Pattern reservedRepoPatterns = Pattern.compile("\\.(git|wiki)$");
public ImageView closeActivity; public ImageView closeActivity;
List<String> organizationsList = new ArrayList<>();
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private AutoCompleteTextView spinner; private AutoCompleteTextView spinner;
private Button createRepo; private Button createRepo;
private EditText repoName; private EditText repoName;
private EditText repoDesc; private EditText repoDesc;
private CheckBox repoAccess; private CheckBox repoAccess;
private String loginUid; private String loginUid;
private String selectedOwner; private String selectedOwner;
private final View.OnClickListener createRepoListener = v -> processNewRepo();
List<String> organizationsList = new ArrayList<>();
//https://github.com/go-gitea/gitea/blob/52cfd2743c0e85b36081cf80a850e6a5901f1865/models/repo.go#L964-L967
final List<String> reservedRepoNames = Arrays.asList(".", "..");
final Pattern reservedRepoPatterns = Pattern.compile("\\.(git|wiki)$");
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -96,8 +88,6 @@ public class CreateRepoActivity extends BaseActivity {
} }
} }
private final View.OnClickListener createRepoListener = v -> processNewRepo();
private void processNewRepo() { private void processNewRepo() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -160,15 +150,11 @@ public class CreateRepoActivity extends BaseActivity {
Call<Repository> call; Call<Repository> call;
if(selectedOwner.equals(loginUid)) { if(selectedOwner.equals(loginUid)) {
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).createCurrentUserRepo(createRepository);
.getApiInterface(ctx)
.createCurrentUserRepo(createRepository);
} }
else { else {
call = RetrofitClient call = RetrofitClient.getApiInterface(ctx).createOrgRepo(selectedOwner, createRepository);
.getApiInterface(ctx)
.createOrgRepo(selectedOwner, createRepository);
} }
call.enqueue(new Callback<Repository>() { call.enqueue(new Callback<Repository>() {
@ -211,9 +197,7 @@ public class CreateRepoActivity extends BaseActivity {
private void getOrganizations(final String userLogin) { private void getOrganizations(final String userLogin) {
Call<List<Organization>> call = RetrofitClient Call<List<Organization>> call = RetrofitClient.getApiInterface(ctx).orgListCurrentUserOrgs(1, 50);
.getApiInterface(ctx)
.orgListCurrentUserOrgs(1, 50);
call.enqueue(new Callback<List<Organization>>() { call.enqueue(new Callback<List<Organization>>() {

View File

@ -33,6 +33,10 @@ import retrofit2.Callback;
public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClickListener { public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClickListener {
private final String[] permissionList = {"Read", "Write", "Admin"};
private final String[] accessControlsList = new String[]{"Code", "Issues", "Pull Request", "Releases", "Wiki", "External Wiki", "External Issues"};
private final boolean[] selectedAccessControlsTrueFalse = new boolean[]{false, false, false, false, false, false, false};
public int permissionSelectedChoice = -1;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private TextView teamName; private TextView teamName;
private TextView teamDesc; private TextView teamDesc;
@ -41,31 +45,8 @@ public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClic
private TextView teamAccessControls; private TextView teamAccessControls;
private TextView teamAccessControlsArray; private TextView teamAccessControlsArray;
private Button createTeamButton; private Button createTeamButton;
private final String[] permissionList = {"Read", "Write", "Admin"};
public int permissionSelectedChoice = -1;
private final String[] accessControlsList = new String[] {
"Code",
"Issues",
"Pull Request",
"Releases",
"Wiki",
"External Wiki",
"External Issues"
};
private List<String> pushAccessList; private List<String> pushAccessList;
private final boolean[] selectedAccessControlsTrueFalse = new boolean[]{
false,
false,
false,
false,
false,
false,
false
};
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -97,9 +78,7 @@ public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClic
teamPermission.setOnClickListener(view -> { teamPermission.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilderPerm = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilderPerm = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.newTeamPermission).setCancelable(permissionSelectedChoice != -1)
.setTitle(R.string.newTeamPermission)
.setCancelable(permissionSelectedChoice != -1)
.setSingleChoiceItems(permissionList, permissionSelectedChoice, (dialogInterface, i) -> { .setSingleChoiceItems(permissionList, permissionSelectedChoice, (dialogInterface, i) -> {
permissionSelectedChoice = i; permissionSelectedChoice = i;
@ -139,14 +118,11 @@ public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClic
teamAccessControlsArray.setText(""); teamAccessControlsArray.setText("");
pushAccessList = Arrays.asList(accessControlsList); pushAccessList = Arrays.asList(accessControlsList);
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setMultiChoiceItems(accessControlsList, selectedAccessControlsTrueFalse, (dialog, which, isChecked) -> {
.setMultiChoiceItems(accessControlsList, selectedAccessControlsTrueFalse, (dialog, which, isChecked) -> {}) }).setTitle(R.string.newTeamAccessControls).setPositiveButton(R.string.okButton, (dialog, which) -> {
.setTitle(R.string.newTeamAccessControls)
.setPositiveButton(R.string.okButton, (dialog, which) -> {
int selectedVal = 0; int selectedVal = 0;
while(selectedVal < selectedAccessControlsTrueFalse.length) while(selectedVal < selectedAccessControlsTrueFalse.length) {
{
boolean value = selectedAccessControlsTrueFalse[selectedVal]; boolean value = selectedAccessControlsTrueFalse[selectedVal];
String repoCode = ""; String repoCode = "";
@ -292,9 +268,7 @@ public class CreateTeamByOrgActivity extends BaseActivity implements View.OnClic
} }
createNewTeamJson.setUnits(newTeamAccessControls); createNewTeamJson.setUnits(newTeamAccessControls);
Call<Team> call3 = RetrofitClient Call<Team> call3 = RetrofitClient.getApiInterface(ctx).orgCreateTeam(orgName, createNewTeamJson);
.getApiInterface(ctx)
.orgCreateTeam(orgName, createNewTeamJson);
call3.enqueue(new Callback<Team>() { call3.enqueue(new Callback<Team>() {

View File

@ -9,11 +9,7 @@ import android.util.Log;
import android.view.View; import android.view.View;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.gitnex.tea4j.v2.models.ContentsResponse; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Organization;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.database.api.BaseApi; import org.mian.gitnex.database.api.BaseApi;
@ -95,7 +91,9 @@ public class DeepLinksActivity extends BaseActivity {
hostUrlExternal = hostExternal; hostUrlExternal = hostExternal;
} }
if (hostUrlExternal == null) hostUrlExternal = ""; if(hostUrlExternal == null) {
hostUrlExternal = "";
}
if(hostUri.toLowerCase().contains(hostUrlExternal.toLowerCase())) { if(hostUri.toLowerCase().contains(hostUrlExternal.toLowerCase())) {
@ -131,8 +129,7 @@ public class DeepLinksActivity extends BaseActivity {
finish(); finish();
} }
else { else {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> getUserOrOrg(data.getLastPathSegment()), 500);
getUserOrOrg(data.getLastPathSegment()), 500);
} }
} }
else if(data.getPathSegments().size() == 2) { else if(data.getPathSegments().size() == 2) {
@ -163,8 +160,7 @@ public class DeepLinksActivity extends BaseActivity {
repo = repo.substring(0, repo.length() - 4); repo = repo.substring(0, repo.length() - 4);
} }
String finalRepo = repo; String finalRepo = repo;
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), finalRepo, "repo"), 500);
goToRepoSection(data.getPathSegments().get(0), finalRepo, "repo"), 500);
} }
else { // no action, show options else { // no action, show options
showNoActionButtons(); showNoActionButtons();
@ -183,11 +179,7 @@ public class DeepLinksActivity extends BaseActivity {
issueIntent.putExtra("issueComment", urlSplitted[1]); issueIntent.putExtra("issueComment", urlSplitted[1]);
} }
IssueContext issue = new IssueContext( IssueContext issue = new IssueContext(new RepositoryContext(data.getPathSegments().get(0), data.getPathSegments().get(1), ctx), Integer.parseInt(data.getLastPathSegment()), "Issue");
new RepositoryContext(data.getPathSegments().get(0), data.getPathSegments().get(1), ctx),
Integer.parseInt(data.getLastPathSegment()),
"Issue"
);
issue.getRepository().saveToDB(ctx); issue.getRepository().saveToDB(ctx);
@ -197,12 +189,10 @@ public class DeepLinksActivity extends BaseActivity {
finish(); finish();
} }
else if(Objects.requireNonNull(data.getLastPathSegment()).contains("issues")) { else if(Objects.requireNonNull(data.getLastPathSegment()).contains("issues")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issue"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issue"), 500);
} }
else if(data.getLastPathSegment().equals("new")) { else if(data.getLastPathSegment().equals("new")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issueNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "issueNew"), 500);
} }
else { else {
ctx.startActivity(mainIntent); ctx.startActivity(mainIntent);
@ -225,8 +215,7 @@ public class DeepLinksActivity extends BaseActivity {
} }
else if(Objects.requireNonNull(data.getLastPathSegment()).contains("pulls")) { else if(Objects.requireNonNull(data.getLastPathSegment()).contains("pulls")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pull"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pull"), 500);
} }
else if(data.getLastPathSegment().equals("files")) { // pr diff else if(data.getLastPathSegment().equals("files")) { // pr diff
new Handler(Looper.getMainLooper()).postDelayed(() -> { new Handler(Looper.getMainLooper()).postDelayed(() -> {
@ -241,36 +230,29 @@ public class DeepLinksActivity extends BaseActivity {
} }
else if(data.getPathSegments().get(2).equals("compare")) { // new pull request else if(data.getPathSegments().get(2).equals("compare")) { // new pull request
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pullNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "pullNew"), 500);
} }
else if(data.getPathSegments().get(2).equals("commit")) { else if(data.getPathSegments().get(2).equals("commit")) {
repoIntent.putExtra("sha", data.getLastPathSegment()); repoIntent.putExtra("sha", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commit"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commit"), 500);
} }
else if(data.getPathSegments().get(2).equals("commits")) { // commits list else if(data.getPathSegments().get(2).equals("commits")) { // commits list
String branch = data.getLastPathSegment(); String branch = data.getLastPathSegment();
repoIntent.putExtra("branchName", branch); repoIntent.putExtra("branchName", branch);
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commitsList"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "commitsList"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestones") && data.getLastPathSegment().equals("new")) { // new milestone else if(data.getPathSegments().get(2).equals("milestones") && data.getLastPathSegment().equals("new")) { // new milestone
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestonesNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestonesNew"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestones")) { // milestones else if(data.getPathSegments().get(2).equals("milestones")) { // milestones
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
} }
else if(data.getPathSegments().get(2).equals("milestone")) { // milestone else if(data.getPathSegments().get(2).equals("milestone")) { // milestone
repoIntent.putExtra("milestoneId", data.getLastPathSegment()); repoIntent.putExtra("milestoneId", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "milestones"), 500);
} }
else if(data.getPathSegments().get(2).equals("releases") && data.getLastPathSegment().equals("new")) { // new release else if(data.getPathSegments().get(2).equals("releases") && data.getLastPathSegment().equals("new")) { // new release
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "newRelease"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "newRelease"), 500);
} }
else if(data.getPathSegments().get(2).equals("releases")) { // releases else if(data.getPathSegments().get(2).equals("releases")) { // releases
if(data.getPathSegments().size() == 5) { if(data.getPathSegments().size() == 5) {
@ -278,26 +260,20 @@ public class DeepLinksActivity extends BaseActivity {
repoIntent.putExtra("releaseTagName", data.getLastPathSegment()); repoIntent.putExtra("releaseTagName", data.getLastPathSegment());
} }
} }
new Handler(Looper.getMainLooper()).postDelayed( new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "releases"), 500);
() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1),
"releases"), 500);
} }
else if(data.getPathSegments().get(2).equals("labels")) { // labels else if(data.getPathSegments().get(2).equals("labels")) { // labels
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "labels"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "labels"), 500);
} }
else if(data.getPathSegments().get(2).equals("settings")) { // repo settings else if(data.getPathSegments().get(2).equals("settings")) { // repo settings
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "settings"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "settings"), 500);
} }
else if(data.getLastPathSegment().equals("branches")) { // branches list else if(data.getLastPathSegment().equals("branches")) { // branches list
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branchesList"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branchesList"), 500);
} }
else if(data.getPathSegments().size() == 5 && data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // branch else if(data.getPathSegments().size() == 5 && data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // branch
repoIntent.putExtra("selectedBranch", data.getLastPathSegment()); repoIntent.putExtra("selectedBranch", data.getLastPathSegment());
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branch"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "branch"), 500);
} }
else if(data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // file/dir else if(data.getPathSegments().get(2).equals("src") && data.getPathSegments().get(3).equals("branch")) { // file/dir
StringBuilder filePath = new StringBuilder(); StringBuilder filePath = new StringBuilder();
@ -308,19 +284,15 @@ public class DeepLinksActivity extends BaseActivity {
filePath.append("/"); filePath.append("/");
} }
filePath.deleteCharAt(filePath.toString().length() - 1); filePath.deleteCharAt(filePath.toString().length() - 1);
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> getFile(data.getPathSegments().get(0), data.getPathSegments().get(1), filePath.toString(), data.getPathSegments().get(4)), 500);
getFile(data.getPathSegments().get(0),
data.getPathSegments().get(1), filePath.toString(), data.getPathSegments().get(4)), 500);
} }
else if(data.getPathSegments().get(2).equals("wiki")) { // wiki else if(data.getPathSegments().get(2).equals("wiki")) { // wiki
if(data.getQueryParameter("action") != null && data.getQueryParameter("action").equalsIgnoreCase("_new")) { if(data.getQueryParameter("action") != null && data.getQueryParameter("action").equalsIgnoreCase("_new")) {
new Handler(Looper.getMainLooper()).postDelayed(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wikiNew"), 500);
goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wikiNew"), 500);
} }
else { else {
new Handler(Looper.getMainLooper()).postDelayed( new Handler(Looper.getMainLooper()).postDelayed(() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wiki"), 500);
() -> goToRepoSection(data.getPathSegments().get(0), data.getPathSegments().get(1), "wiki"), 500);
} }
} }
else { // no action, show options else { // no action, show options
@ -352,9 +324,7 @@ public class DeepLinksActivity extends BaseActivity {
Integer port = data.getPort() >= 0 ? data.getPort() : null; Integer port = data.getPort() >= 0 ? data.getPort() : null;
URI host = UrlBuilder.fromString(UrlHelper.fixScheme(data.getHost(), "https")) URI host = UrlBuilder.fromString(UrlHelper.fixScheme(data.getHost(), "https")).withPort(port).toUri();
.withPort(port)
.toUri();
AppUtil.openUrlInBrowser(this, String.valueOf(host)); AppUtil.openUrlInBrowser(this, String.valueOf(host));
finish(); finish();
@ -371,9 +341,7 @@ public class DeepLinksActivity extends BaseActivity {
private void getPullRequest(String repoOwner, String repoName, int index) { private void getPullRequest(String repoOwner, String repoName, int index) {
Call<PullRequest> call = RetrofitClient Call<PullRequest> call = RetrofitClient.getApiInterface(ctx).repoGetPullRequest(repoOwner, repoName, (long) index);
.getApiInterface(ctx)
.repoGetPullRequest(repoOwner, repoName, (long) index);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -417,9 +385,7 @@ public class DeepLinksActivity extends BaseActivity {
private void goToRepoSection(String repoOwner, String repoName, String type) { private void goToRepoSection(String repoOwner, String repoName, String type) {
Call<Repository> call = RetrofitClient Call<Repository> call = RetrofitClient.getApiInterface(ctx).repoGet(repoOwner, repoName);
.getApiInterface(ctx)
.repoGet(repoOwner, repoName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -627,4 +593,5 @@ public class DeepLinksActivity extends BaseActivity {
}); });
} }
} }
} }

View File

@ -29,20 +29,15 @@ public class DiffActivity extends BaseActivity {
@Override @Override
public void handleOnBackPressed() { public void handleOnBackPressed() {
if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) { if(getSupportFragmentManager().findFragmentById(R.id.fragment_container) instanceof DiffFragment) {
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction() }
.replace(R.id.fragment_container, fragment) else {
.commit();
} else {
finish(); finish();
} }
} }
}); });
getSupportFragmentManager() getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
} }

View File

@ -11,12 +11,7 @@ import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import org.gitnex.tea4j.v2.models.EditIssueOption; import org.gitnex.tea4j.v2.models.EditIssueOption;
import org.gitnex.tea4j.v2.models.Issue; import org.gitnex.tea4j.v2.models.Issue;
@ -33,12 +28,7 @@ import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -48,21 +38,17 @@ import retrofit2.Callback;
public class EditIssueActivity extends BaseActivity implements View.OnClickListener { public class EditIssueActivity extends BaseActivity implements View.OnClickListener {
private final String msState = "open";
private final LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private int resultLimit; private int resultLimit;
private EditText editIssueTitle; private EditText editIssueTitle;
private EditText editIssueDescription; private EditText editIssueDescription;
private TextView editIssueDueDate; private TextView editIssueDueDate;
private Button editIssueButton; private Button editIssueButton;
private AutoCompleteTextView editIssueMilestoneSpinner; private AutoCompleteTextView editIssueMilestoneSpinner;
private final String msState = "open";
private int milestoneId = 0; private int milestoneId = 0;
private Date currentDate = null; private Date currentDate = null;
private LinkedHashMap<String, Milestone> milestonesList = new LinkedHashMap<>();
private IssueContext issue; private IssueContext issue;
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
@ -152,8 +138,7 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
} }
disableProcessButton(); disableProcessButton();
editIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), editIssueTitleForm, editIssueDescriptionForm, editIssue(issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getIssueIndex(), editIssueTitleForm, editIssueDescriptionForm, milestoneId);
milestoneId);
} }
private void editIssue(String repoOwner, String repoName, int issueIndex, String title, String description, int milestoneId) { private void editIssue(String repoOwner, String repoName, int issueIndex, String title, String description, int milestoneId) {
@ -164,9 +149,7 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
issueData.setDueDate(currentDate); issueData.setDueDate(currentDate);
issueData.setMilestone((long) milestoneId); issueData.setMilestone((long) milestoneId);
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueEditIssue(repoOwner, repoName, (long) issueIndex, issueData);
.getApiInterface(ctx)
.issueEditIssue(repoOwner, repoName, (long) issueIndex, issueData);
call.enqueue(new Callback<Issue>() { call.enqueue(new Callback<Issue>() {
@ -223,8 +206,7 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
final int mMonth = c.get(Calendar.MONTH); final int mMonth = c.get(Calendar.MONTH);
final int mDay = c.get(Calendar.DAY_OF_MONTH); final int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, year, monthOfYear, dayOfMonth) -> {
(view, year, monthOfYear, dayOfMonth) -> {
editIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth)); editIssueDueDate.setText(getString(R.string.setDueDate, year, (monthOfYear + 1), dayOfMonth));
currentDate = new Date(year - 1900, monthOfYear, dayOfMonth); currentDate = new Date(year - 1900, monthOfYear, dayOfMonth);
}, mYear, mMonth, mDay); }, mYear, mMonth, mDay);
@ -239,9 +221,7 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
private void getIssue(final String repoOwner, final String repoName, int issueIndex, int resultLimit) { private void getIssue(final String repoOwner, final String repoName, int issueIndex, int resultLimit) {
Call<Issue> call = RetrofitClient Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.getApiInterface(ctx)
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -297,8 +277,7 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
milestoneId = 0; milestoneId = 0;
} }
else if(view instanceof TextView) { else if(view instanceof TextView) {
milestoneId = Math.toIntExact( milestoneId = Math.toIntExact(Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId());
Objects.requireNonNull(milestonesList.get(((TextView) view).getText().toString())).getId());
} }
}); });
@ -306,7 +285,8 @@ public class EditIssueActivity extends BaseActivity implements View.OnClickListe
if(currentMilestone != null) { if(currentMilestone != null) {
milestoneId = Math.toIntExact(currentMilestone.getId()); milestoneId = Math.toIntExact(currentMilestone.getId());
editIssueMilestoneSpinner.setText(currentMilestone.getTitle(), false); editIssueMilestoneSpinner.setText(currentMilestone.getTitle(), false);
} else { }
else {
milestoneId = 0; milestoneId = 0;
editIssueMilestoneSpinner.setText(getString(R.string.issueCreatedNoMilestone), false); editIssueMilestoneSpinner.setText(getString(R.string.issueCreatedNoMilestone), false);
} }

View File

@ -8,11 +8,7 @@ import android.graphics.Bitmap;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.text.method.ScrollingMovementMethod; import android.text.method.ScrollingMovementMethod;
import android.view.Gravity; import android.view.*;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts; import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
@ -23,12 +19,7 @@ import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.ActivityFileViewBinding; import org.mian.gitnex.databinding.ActivityFileViewBinding;
import org.mian.gitnex.fragments.BottomSheetFileViewerFragment; import org.mian.gitnex.fragments.BottomSheetFileViewerFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Constants;
import org.mian.gitnex.helpers.Images;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.mian.gitnex.notifications.Notifications; import org.mian.gitnex.notifications.Notifications;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
@ -48,11 +39,68 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
private ActivityFileViewBinding binding; private ActivityFileViewBinding binding;
private ContentsResponse file; private ContentsResponse file;
private RepositoryContext repository; private RepositoryContext repository;
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
assert result.getData() != null;
try {
OutputStream outputStream = getContentResolver().openOutputStream(result.getData().getData());
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, ctx.getPackageName()).setContentTitle(getString(R.string.fileViewerNotificationTitleStarted))
.setContentText(getString(R.string.fileViewerNotificationDescriptionStarted, file.getName())).setSmallIcon(R.drawable.gitnex_transparent).setPriority(NotificationCompat.PRIORITY_LOW)
.setChannelId(Constants.downloadNotificationChannelId).setProgress(100, 0, false).setOngoing(true);
int notificationId = Notifications.uniqueNotificationId(ctx);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
Thread thread = new Thread(() -> {
try {
Call<ResponseBody> call = RetrofitClient.getWebInterface(ctx).getFileContents(repository.getOwner(), repository.getName(), repository.getBranchRef(), file.getPath());
Response<ResponseBody> response = call.execute();
assert response.body() != null;
AppUtil.copyProgress(response.body().byteStream(), outputStream, file.getSize(), progress -> {
builder.setProgress(100, progress, false);
notificationManager.notify(notificationId, builder.build());
});
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFinished)).setContentText(getString(R.string.fileViewerNotificationDescriptionFinished, file.getName()));
}
catch(IOException ignored) {
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFailed)).setContentText(getString(R.string.fileViewerNotificationDescriptionFailed, file.getName()));
}
finally {
builder.setProgress(0, 0, false).setOngoing(false);
notificationManager.notify(notificationId, builder.build());
}
});
thread.start();
}
catch(IOException ignored) {
}
}
});
private boolean renderMd = false; private boolean renderMd = false;
private boolean processable = false; private boolean processable = false;
public ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
public ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 200) { if(result.getResultCode() == 200) {
assert result.getData() != null; assert result.getData() != null;
if(result.getData().getBooleanExtra("fileModified", false)) { if(result.getData().getBooleanExtra("fileModified", false)) {
@ -93,9 +141,7 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
Thread thread = new Thread(() -> { Thread thread = new Thread(() -> {
Call<ResponseBody> call = RetrofitClient Call<ResponseBody> call = RetrofitClient.getWebInterface(ctx).getFileContents(owner, repo, ref, filename);
.getWebInterface(ctx)
.getFileContents(owner, repo, ref, filename);
try { try {
@ -153,7 +199,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.contents.setVisibility(View.GONE); binding.contents.setVisibility(View.GONE);
binding.markdownFrame.setVisibility(View.VISIBLE); binding.markdownFrame.setVisibility(View.VISIBLE);
} else { }
else {
binding.markdownFrame.setVisibility(View.GONE); binding.markdownFrame.setVisibility(View.GONE);
binding.contents.setVisibility(View.VISIBLE); binding.contents.setVisibility(View.VISIBLE);
} }
@ -178,14 +225,16 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.markdownTv.setTypeface(null, Typeface.BOLD); binding.markdownTv.setTypeface(null, Typeface.BOLD);
}); });
} }
} else { }
else {
runOnUiThread(() -> { runOnUiThread(() -> {
binding.markdownTv.setText(""); binding.markdownTv.setText("");
binding.progressBar.setVisibility(View.GONE); binding.progressBar.setVisibility(View.GONE);
}); });
} }
} else { }
else {
switch(response.code()) { switch(response.code()) {
@ -206,7 +255,9 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
} }
} }
} catch(IOException ignored) {} }
catch(IOException ignored) {
}
}); });
@ -221,11 +272,9 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
inflater.inflate(R.menu.generic_nav_dotted_menu, menu); inflater.inflate(R.menu.generic_nav_dotted_menu, menu);
inflater.inflate(R.menu.markdown_switcher, menu); inflater.inflate(R.menu.markdown_switcher, menu);
if(!FilenameUtils.getExtension(file.getName()) if(!FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("md")) {
.equalsIgnoreCase("md")) {
menu.getItem(0) menu.getItem(0).setVisible(false);
.setVisible(false);
} }
return true; return true;
@ -241,7 +290,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
finish(); finish();
return true; return true;
} else if(id == R.id.genericMenu) { }
else if(id == R.id.genericMenu) {
BottomSheetFileViewerFragment bottomSheet = new BottomSheetFileViewerFragment(); BottomSheetFileViewerFragment bottomSheet = new BottomSheetFileViewerFragment();
Bundle opts = repository.getBundle(); Bundle opts = repository.getBundle();
@ -250,7 +300,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
bottomSheet.show(getSupportFragmentManager(), "fileViewerBottomSheet"); bottomSheet.show(getSupportFragmentManager(), "fileViewerBottomSheet");
return true; return true;
} else if(id == R.id.markdown) { }
else if(id == R.id.markdown) {
if(!renderMd) { if(!renderMd) {
if(binding.markdown.getAdapter() == null) { if(binding.markdown.getAdapter() == null) {
@ -261,7 +312,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
binding.markdownFrame.setVisibility(View.VISIBLE); binding.markdownFrame.setVisibility(View.VISIBLE);
renderMd = true; renderMd = true;
} else { }
else {
binding.markdownFrame.setVisibility(View.GONE); binding.markdownFrame.setVisibility(View.GONE);
binding.contents.setVisibility(View.VISIBLE); binding.contents.setVisibility(View.VISIBLE);
@ -270,7 +322,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
return true; return true;
} else { }
else {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
@ -293,8 +346,7 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
if("editFile".equals(text)) { if("editFile".equals(text)) {
if(binding.contents.getContent() != null && if(binding.contents.getContent() != null && !binding.contents.getContent().isEmpty()) {
!binding.contents.getContent().isEmpty()) {
Intent intent = repository.getIntent(ctx, CreateFileActivity.class); Intent intent = repository.getIntent(ctx, CreateFileActivity.class);
@ -305,7 +357,8 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
editFileLauncher.launch(intent); editFileLauncher.launch(intent);
} else { }
else {
Toasty.error(ctx, getString(R.string.fileTypeCannotBeEdited)); Toasty.error(ctx, getString(R.string.fileTypeCannotBeEdited));
} }
} }
@ -323,72 +376,6 @@ public class FileViewActivity extends BaseActivity implements BottomSheetListene
} }
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
assert result.getData() != null;
try {
OutputStream outputStream = getContentResolver().openOutputStream(result.getData().getData());
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, ctx.getPackageName())
.setContentTitle(getString(R.string.fileViewerNotificationTitleStarted))
.setContentText(getString(R.string.fileViewerNotificationDescriptionStarted, file.getName()))
.setSmallIcon(R.drawable.gitnex_transparent)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setChannelId(Constants.downloadNotificationChannelId)
.setProgress(100, 0, false)
.setOngoing(true);
int notificationId = Notifications.uniqueNotificationId(ctx);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);;
notificationManager.notify(notificationId, builder.build());
Thread thread = new Thread(() -> {
try {
Call<ResponseBody> call = RetrofitClient
.getWebInterface(ctx)
.getFileContents(repository.getOwner(), repository.getName(), repository.getBranchRef(), file.getPath());
Response<ResponseBody> response = call.execute();
assert response.body() != null;
AppUtil.copyProgress(response.body().byteStream(), outputStream, file.getSize(), progress -> {
builder.setProgress(100, progress, false);
notificationManager.notify(notificationId, builder.build());
});
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFinished))
.setContentText(getString(R.string.fileViewerNotificationDescriptionFinished, file.getName()));
} catch(IOException ignored) {
builder.setContentTitle(getString(R.string.fileViewerNotificationTitleFailed))
.setContentText(getString(R.string.fileViewerNotificationDescriptionFailed, file.getName()));
} finally {
builder.setProgress(0,0,false)
.setOngoing(false);
notificationManager.notify(notificationId, builder.build());
}
});
thread.start();
} catch(IOException ignored) {}
}
});
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@ -8,12 +8,7 @@ import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.util.Log; import android.util.Log;
import android.view.Gravity; import android.view.*;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
@ -31,14 +26,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable; import com.amulyakhare.textdrawable.TextDrawable;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.vdurmont.emoji.EmojiParser; import com.vdurmont.emoji.EmojiParser;
import org.gitnex.tea4j.v2.models.EditIssueOption; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Issue;
import org.gitnex.tea4j.v2.models.IssueLabelsOption;
import org.gitnex.tea4j.v2.models.Label;
import org.gitnex.tea4j.v2.models.PullRequest;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.User;
import org.gitnex.tea4j.v2.models.WatchInfo;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.actions.AssigneesActions; import org.mian.gitnex.actions.AssigneesActions;
import org.mian.gitnex.actions.LabelsActions; import org.mian.gitnex.actions.LabelsActions;
@ -54,29 +42,14 @@ import org.mian.gitnex.databinding.CustomPrInfoDialogBinding;
import org.mian.gitnex.fragments.BottomSheetReplyFragment; import org.mian.gitnex.fragments.BottomSheetReplyFragment;
import org.mian.gitnex.fragments.BottomSheetSingleIssueFragment; import org.mian.gitnex.fragments.BottomSheetSingleIssueFragment;
import org.mian.gitnex.fragments.IssuesFragment; import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.DividerItemDecorator;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import org.mian.gitnex.viewmodels.IssueCommentsViewModel; import org.mian.gitnex.viewmodels.IssueCommentsViewModel;
import org.mian.gitnex.views.ReactionList; import org.mian.gitnex.views.ReactionList;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
@ -87,35 +60,32 @@ import retrofit2.Response;
public class IssueDetailActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener, BottomSheetListener { public class IssueDetailActivity extends BaseActivity implements LabelsListAdapter.LabelsListAdapterListener, AssigneesListAdapter.AssigneesListAdapterListener, BottomSheetListener {
public static boolean singleIssueUpdate = false;
public static boolean commentPosted = false;
private final List<Label> labelsList = new ArrayList<>();
private final List<User> assigneesList = new ArrayList<>();
public boolean commentEdited = false;
private IssueCommentsAdapter adapter; private IssueCommentsAdapter adapter;
private String repoOwner; private String repoOwner;
private String repoName; private String repoName;
private int issueIndex; private int issueIndex;
private String issueCreator; private String issueCreator;
private IssueContext issue; private IssueContext issue;
private LabelsListAdapter labelsAdapter; private LabelsListAdapter labelsAdapter;
private AssigneesListAdapter assigneesAdapter; private AssigneesListAdapter assigneesAdapter;
private List<Integer> currentLabelsIds = new ArrayList<>(); private List<Integer> currentLabelsIds = new ArrayList<>();
private List<Integer> labelsIds = new ArrayList<>(); private List<Integer> labelsIds = new ArrayList<>();
private final List<Label> labelsList = new ArrayList<>();
private final List<User> assigneesList = new ArrayList<>();
private List<String> assigneesListData = new ArrayList<>(); private List<String> assigneesListData = new ArrayList<>();
private List<String> currentAssignees = new ArrayList<>(); private List<String> currentAssignees = new ArrayList<>();
private ActivityIssueDetailBinding viewBinding; private ActivityIssueDetailBinding viewBinding;
private MaterialAlertDialogBuilder materialAlertDialogBuilder; private MaterialAlertDialogBuilder materialAlertDialogBuilder;
public static boolean singleIssueUpdate = false;
public boolean commentEdited = false;
public static boolean commentPosted = false;
private IssueCommentsViewModel issueCommentsModel; private IssueCommentsViewModel issueCommentsModel;
private Runnable showMenu = () -> {
public ActivityResultLauncher<Intent> editIssueLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), };
result -> { private boolean loadingFinishedIssue = false;
private boolean loadingFinishedPr = false;
private boolean loadingFinishedRepo = false;
public ActivityResultLauncher<Intent> editIssueLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 200) { if(result.getResultCode() == 200) {
assert result.getData() != null; assert result.getData() != null;
if(result.getData().getBooleanExtra("issueEdited", false)) { if(result.getData().getBooleanExtra("issueEdited", false)) {
@ -174,9 +144,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> { viewBinding.pullToRefresh.setOnRefreshListener(() -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
viewBinding.pullToRefresh.setRefreshing(false); viewBinding.pullToRefresh.setRefreshing(false);
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx);
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx);
}, 500)); }, 500));
@ -212,7 +180,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
@Override @Override
public void labelsInterface(List<String> data) { } public void labelsInterface(List<String> data) {
}
@Override @Override
public void labelsIdsInterface(List<Integer> data) { public void labelsIdsInterface(List<Integer> data) {
@ -230,8 +199,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
assigneesAdapter.updateList(currentAssignees); assigneesAdapter.updateList(currentAssignees);
viewBinding.progressBar.setVisibility(View.VISIBLE); viewBinding.progressBar.setVisibility(View.VISIBLE);
CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate( CustomAssigneesSelectionDialogBinding assigneesBinding = CustomAssigneesSelectionDialogBinding.inflate(LayoutInflater.from(ctx));
LayoutInflater.from(ctx));
View view = assigneesBinding.getRoot(); View view = assigneesBinding.getRoot();
materialAlertDialogBuilder.setView(view); materialAlertDialogBuilder.setView(view);
@ -279,9 +247,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
EditIssueOption updateAssigneeJson = new EditIssueOption().assignees(assigneesListData); EditIssueOption updateAssigneeJson = new EditIssueOption().assignees(assigneesListData);
Call<Issue> call3 = RetrofitClient Call<Issue> call3 = RetrofitClient.getApiInterface(ctx).issueEditIssue(repoOwner, repoName, (long) issueIndex, updateAssigneeJson);
.getApiInterface(ctx)
.issueEditIssue(repoOwner, repoName, (long) issueIndex, updateAssigneeJson);
call3.enqueue(new Callback<>() { call3.enqueue(new Callback<>() {
@ -335,9 +301,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
IssueLabelsOption patchIssueLabels = new IssueLabelsOption(); IssueLabelsOption patchIssueLabels = new IssueLabelsOption();
patchIssueLabels.setLabels(labelIds); patchIssueLabels.setLabels(labelIds);
Call<List<Label>> call = RetrofitClient Call<List<Label>> call = RetrofitClient.getApiInterface(ctx).issueReplaceLabels(repoOwner, repoName, (long) issueIndex, patchIssueLabels);
.getApiInterface(ctx)
.issueReplaceLabels(repoOwner, repoName, (long) issueIndex, patchIssueLabels);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -383,12 +347,10 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
}); });
} }
private Runnable showMenu = () -> {};
private boolean loadingFinishedIssue = false;
private boolean loadingFinishedPr = false;
private boolean loadingFinishedRepo = false;
private void updateMenuState() { private void updateMenuState() {
if(loadingFinishedIssue && loadingFinishedPr && loadingFinishedRepo) showMenu.run(); if(loadingFinishedIssue && loadingFinishedPr && loadingFinishedRepo) {
showMenu.run();
}
} }
@Override @Override
@ -402,7 +364,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
inflater.inflate(R.menu.pr_info_menu, menu); inflater.inflate(R.menu.pr_info_menu, menu);
} }
} }
showMenu = () -> {}; // reset Runnable showMenu = () -> {
}; // reset Runnable
}; };
updateMenuState(); updateMenuState();
return true; return true;
@ -415,8 +378,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
if(id == android.R.id.home) { if(id == android.R.id.home) {
if(issue.hasIssue() && getIntent().getStringExtra("openedFromLink") != null && if(issue.hasIssue() && getIntent().getStringExtra("openedFromLink") != null && getIntent().getStringExtra("openedFromLink").equals("true")) {
getIntent().getStringExtra("openedFromLink").equals("true")) {
Intent intent = issue.getRepository().getIntent(ctx, RepoDetailActivity.class); Intent intent = issue.getRepository().getIntent(ctx, RepoDetailActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
@ -466,9 +428,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.scrollViewComments.post(() -> { viewBinding.scrollViewComments.post(() -> {
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx, () -> viewBinding.scrollViewComments.fullScroll(ScrollView.FOCUS_DOWN));
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx, () -> viewBinding.scrollViewComments.fullScroll(ScrollView.FOCUS_DOWN));
commentPosted = false; commentPosted = false;
}); });
@ -478,9 +438,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.scrollViewComments.post(() -> { viewBinding.scrollViewComments.post(() -> {
issueCommentsModel issueCommentsModel.loadIssueComments(repoOwner, repoName, issueIndex, ctx);
.loadIssueComments(repoOwner, repoName, issueIndex,
ctx);
commentEdited = false; commentEdited = false;
}); });
} }
@ -501,8 +459,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
private void fetchDataAsync(String owner, String repo, int index) { private void fetchDataAsync(String owner, String repo, int index) {
issueCommentsModel.getIssueCommentList(owner, repo, index, ctx) issueCommentsModel.getIssueCommentList(owner, repo, index, ctx).observe(this, issueCommentsMain -> {
.observe(this, issueCommentsMain -> {
assert issueCommentsMain != null; assert issueCommentsMain != null;
@ -531,8 +488,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
return; return;
} }
Call<Issue> call = RetrofitClient.getApiInterface(ctx) Call<Issue> call = RetrofitClient.getApiInterface(ctx).issueGetIssue(repoOwner, repoName, (long) issueIndex);
.issueGetIssue(repoOwner, repoName, (long) issueIndex);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -575,9 +531,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
private void getSubscribed() { private void getSubscribed() {
RetrofitClient.getApiInterface(ctx) RetrofitClient.getApiInterface(ctx).issueCheckSubscription(repoOwner, repoName, (long) issueIndex).enqueue(new Callback<>() {
.issueCheckSubscription(repoOwner, repoName, (long) issueIndex)
.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<WatchInfo> call, @NonNull Response<WatchInfo> response) { public void onResponse(@NonNull Call<WatchInfo> call, @NonNull Response<WatchInfo> response) {
@ -602,7 +556,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
private void initWithIssue() { private void initWithIssue() {
if(!issue.getRepository().hasRepository()) { if(!issue.getRepository().hasRepository()) {
getRepoInfo(); getRepoInfo();
} else { }
else {
loadingFinishedRepo = true; loadingFinishedRepo = true;
} }
loadingFinishedIssue = true; loadingFinishedIssue = true;
@ -633,7 +588,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
updateMenuState(); updateMenuState();
viewBinding.issuePrState.setImageResource(R.drawable.ic_issue); viewBinding.issuePrState.setImageResource(R.drawable.ic_issue);
ImageViewCompat.setImageTintList(viewBinding.issuePrState, ColorStateList.valueOf(ctx.getResources().getColor(R.color.iconIssuePrClosedColor))); ImageViewCompat.setImageTintList(viewBinding.issuePrState, ColorStateList.valueOf(ctx.getResources().getColor(R.color.iconIssuePrClosedColor)));
} else { }
else {
loadingFinishedPr = true; loadingFinishedPr = true;
updateMenuState(); updateMenuState();
viewBinding.issuePrState.setImageResource(R.drawable.ic_issue); viewBinding.issuePrState.setImageResource(R.drawable.ic_issue);
@ -645,10 +601,9 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
final String timeFormat = tinyDb.getString("dateFormat", "pretty"); final String timeFormat = tinyDb.getString("dateFormat", "pretty");
issueCreator = issue.getIssue().getUser().getLogin(); issueCreator = issue.getIssue().getUser().getLogin();
PicassoService.getInstance(ctx).get().load(issue.getIssue().getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated) PicassoService.getInstance(ctx).get().load(issue.getIssue().getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(8, 0)).resize(120, 120).centerCrop()
.transform(new RoundedTransformation(8, 0)).resize(120, 120).centerCrop().into(viewBinding.assigneeAvatar); .into(viewBinding.assigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(getResources(), R.color.lightGray, null) + "'>" + appCtx.getResources() String issueNumber_ = "<font color='" + ResourcesCompat.getColor(getResources(), R.color.lightGray, null) + "'>" + appCtx.getResources().getString(R.string.hash) + issue.getIssue().getNumber() + "</font>";
.getString(R.string.hash) + issue.getIssue().getNumber() + "</font>";
viewBinding.issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + EmojiParser.parseToUnicode(issue.getIssue().getTitle()), HtmlCompat.FROM_HTML_MODE_LEGACY)); viewBinding.issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + EmojiParser.parseToUnicode(issue.getIssue().getTitle()), HtmlCompat.FROM_HTML_MODE_LEGACY));
String cleanIssueDescription = issue.getIssue().getBody().trim(); String cleanIssueDescription = issue.getIssue().getBody().trim();
@ -681,9 +636,8 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
ImageView assigneesView = new ImageView(ctx); ImageView assigneesView = new ImageView(ctx);
PicassoService.getInstance(ctx).get().load(issue.getIssue().getAssignees().get(i).getAvatarUrl()) PicassoService.getInstance(ctx).get().load(issue.getIssue().getAssignees().get(i).getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(48, 0)).resize(96, 96)
.placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(48, 0)).resize(96, 96).centerCrop() .centerCrop().into(assigneesView);
.into(assigneesView);
viewBinding.frameAssignees.addView(assigneesView); viewBinding.frameAssignees.addView(assigneesView);
assigneesView.setLayoutParams(params1); assigneesView.setLayoutParams(params1);
@ -721,8 +675,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
viewBinding.assigneesScrollView.setVisibility(View.GONE); viewBinding.assigneesScrollView.setVisibility(View.GONE);
} }
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getIssue().getLabels() != null) { if(issue.getIssue().getLabels() != null) {
@ -743,10 +696,9 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
int height = AppUtil.getPixelsFromDensity(ctx, 20); int height = AppUtil.getPixelsFromDensity(ctx, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(ctx, 12); int textSize = AppUtil.getPixelsFromScaledDensity(ctx, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT) TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize) .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(ctx, 10))).height(height).endConfig()
.width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(ctx, 10))) .buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(ctx, 18));
.height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(ctx, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
viewBinding.frameLabels.addView(labelsView); viewBinding.frameLabels.addView(labelsView);
@ -765,8 +717,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", locale); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", locale);
String dueDate = formatter.format(issue.getIssue().getDueDate()); String dueDate = formatter.format(issue.getIssue().getDueDate());
viewBinding.issueDueDate.setText(dueDate); viewBinding.issueDueDate.setText(dueDate);
viewBinding.issueDueDate viewBinding.issueDueDate.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getDueDate()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getDueDate()), ctx));
} }
else if(timeFormat.equals("normal1")) { else if(timeFormat.equals("normal1")) {
@ -787,8 +738,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
edited = getString(R.string.colorfulBulletSpan) + getString(R.string.modifiedText); edited = getString(R.string.colorfulBulletSpan) + getString(R.string.modifiedText);
viewBinding.issueModified.setVisibility(View.VISIBLE); viewBinding.issueModified.setVisibility(View.VISIBLE);
viewBinding.issueModified.setText(edited); viewBinding.issueModified.setText(edited);
viewBinding.issueModified viewBinding.issueModified.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getUpdatedAt()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getUpdatedAt()), ctx));
} }
else { else {
@ -821,8 +771,7 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
if(timeFormat.equals("pretty")) { if(timeFormat.equals("pretty")) {
viewBinding.issueCreatedTime viewBinding.issueCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getCreatedAt()), ctx));
.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(issue.getIssue().getCreatedAt()), ctx));
} }
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -909,4 +858,5 @@ public class IssueDetailActivity extends BaseActivity implements LabelsListAdapt
} }
}); });
} }
} }

View File

@ -3,30 +3,17 @@ package org.mian.gitnex.activities;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.ArrayAdapter; import android.widget.*;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import org.gitnex.tea4j.v2.models.AccessToken; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.CreateAccessTokenOption;
import org.gitnex.tea4j.v2.models.GeneralAPISettings;
import org.gitnex.tea4j.v2.models.ServerVersion;
import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.database.api.BaseApi; import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityLoginBinding; import org.mian.gitnex.databinding.ActivityLoginBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.NetworkStatusObserver;
import org.mian.gitnex.helpers.PathsHelper;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.UrlHelper;
import org.mian.gitnex.helpers.Version;
import org.mian.gitnex.structs.Protocol; import org.mian.gitnex.structs.Protocol;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -43,15 +30,12 @@ import retrofit2.Callback;
public class LoginActivity extends BaseActivity { public class LoginActivity extends BaseActivity {
private enum LoginType {BASIC, TOKEN}
private Button loginButton; private Button loginButton;
private EditText instanceUrlET, loginUidET, loginPassword, otpCode, loginTokenCode; private EditText instanceUrlET, loginUidET, loginPassword, otpCode, loginTokenCode;
private AutoCompleteTextView protocolSpinner; private AutoCompleteTextView protocolSpinner;
private RadioGroup loginMethod; private RadioGroup loginMethod;
private String device_id = "token"; private String device_id = "token";
private String selectedProtocol; private String selectedProtocol;
private URI instanceUrl; private URI instanceUrl;
private Version giteaVersion; private Version giteaVersion;
private int maxResponseItems = 50; private int maxResponseItems = 50;
@ -96,7 +80,8 @@ public class LoginActivity extends BaseActivity {
if(R.id.loginToken == loginMethod.getCheckedRadioButtonId()) { if(R.id.loginToken == loginMethod.getCheckedRadioButtonId()) {
AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE);
} else { }
else {
AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE);
} }
@ -105,7 +90,8 @@ public class LoginActivity extends BaseActivity {
if(checkedId == R.id.loginToken) { if(checkedId == R.id.loginToken) {
AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.GONE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.VISIBLE);
} else { }
else {
AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout)); AppUtil.setMultiVisibility(View.VISIBLE, findViewById(R.id.login_uidLayout), findViewById(R.id.login_passwdLayout), findViewById(R.id.otpCodeLayout));
findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE); findViewById(R.id.loginTokenCodeLayout).setVisibility(View.GONE);
} }
@ -114,7 +100,8 @@ public class LoginActivity extends BaseActivity {
networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> { networkStatusObserver.registerNetworkStatusListener(hasNetworkConnection -> runOnUiThread(() -> {
if(hasNetworkConnection) { if(hasNetworkConnection) {
enableProcessButton(); enableProcessButton();
} else { }
else {
disableProcessButton(); disableProcessButton();
loginButton.setText(getResources().getString(R.string.btnLogin)); loginButton.setText(getResources().getString(R.string.btnLogin));
Toasty.error(ctx, getResources().getString(R.string.checkNetConnection)); Toasty.error(ctx, getResources().getString(R.string.checkNetConnection));
@ -148,8 +135,7 @@ public class LoginActivity extends BaseActivity {
URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET.getText().toString().replaceAll("[\\uFEFF|#]", "").trim(), "http")).toUri(); URI rawInstanceUrl = UrlBuilder.fromString(UrlHelper.fixScheme(instanceUrlET.getText().toString().replaceAll("[\\uFEFF|#]", "").trim(), "http")).toUri();
instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(selectedProtocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")) instanceUrl = UrlBuilder.fromUri(rawInstanceUrl).withScheme(selectedProtocol.toLowerCase()).withPath(PathsHelper.join(rawInstanceUrl.getPath(), "/api/v1/")).toUri();
.toUri();
// cache values to make them available the next time the user wants to log in // cache values to make them available the next time the user wants to log in
tinyDB.putString("loginType", loginType.name().toLowerCase()); tinyDB.putString("loginType", loginType.name().toLowerCase());
@ -234,8 +220,7 @@ public class LoginActivity extends BaseActivity {
}); });
} }
private void versionCheck(final String loginUid, final String loginPass, final int loginOTP, final String loginToken, private void versionCheck(final String loginUid, final String loginPass, final int loginOTP, final String loginToken, final LoginType loginType) {
final LoginType loginType) {
Call<ServerVersion> callVersion; Call<ServerVersion> callVersion;
@ -250,7 +235,8 @@ public class LoginActivity extends BaseActivity {
if(loginOTP != 0) { if(loginOTP != 0) {
callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(loginOTP); callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(loginOTP);
} else { }
else {
callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion(); callVersion = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).getVersion();
} }
@ -277,15 +263,12 @@ public class LoginActivity extends BaseActivity {
if(giteaVersion.less(getString(R.string.versionLow))) { if(giteaVersion.less(getString(R.string.versionLow))) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(getString(R.string.versionAlertDialogHeader))
.setTitle(getString(R.string.versionAlertDialogHeader)) .setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion())).setNeutralButton(getString(R.string.cancelButton), (dialog, which) -> {
.setMessage(getResources().getString(R.string.versionUnsupportedOld, version.getVersion()))
.setNeutralButton(getString(R.string.cancelButton), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
enableProcessButton(); enableProcessButton();
}) }).setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
.setPositiveButton(getString(R.string.textContinue), (dialog, which) -> {
dialog.dismiss(); dialog.dismiss();
login(loginType, loginUid, loginPass, loginOTP, loginToken); login(loginType, loginUid, loginPass, loginOTP, loginToken);
@ -432,8 +415,7 @@ public class LoginActivity extends BaseActivity {
Call<Void> delToken; Call<Void> delToken;
if(loginOTP != 0) { if(loginOTP != 0) {
delToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) delToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userDeleteAccessToken(loginOTP, loginUid, String.valueOf(t.getId()));
.userDeleteAccessToken(loginOTP, loginUid, String.valueOf(t.getId()));
} }
else { else {
@ -495,13 +477,11 @@ public class LoginActivity extends BaseActivity {
if(loginOTP != 0) { if(loginOTP != 0) {
callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userCreateToken(loginOTP, loginUid, createUserToken);
.userCreateToken(loginOTP, loginUid, createUserToken);
} }
else { else {
callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null) callCreateToken = RetrofitClient.getApiInterface(ctx, instanceUrl.toString(), credential, null).userCreateToken(loginUid, createUserToken);
.userCreateToken(loginUid, createUserToken);
} }
callCreateToken.enqueue(new Callback<>() { callCreateToken.enqueue(new Callback<>() {
@ -539,9 +519,8 @@ public class LoginActivity extends BaseActivity {
UserAccount account; UserAccount account;
if(!userAccountExists) { if(!userAccountExists) {
long accountId = userAccountsApi long accountId = userAccountsApi.createNewAccount(accountName, instanceUrl.toString(), userDetails.getLogin(), newToken.getSha1(), giteaVersion.toString(), maxResponseItems,
.createNewAccount(accountName, instanceUrl.toString(), userDetails.getLogin(), newToken.getSha1(), defaultPagingNumber);
giteaVersion.toString(), maxResponseItems, defaultPagingNumber);
account = userAccountsApi.getAccountById((int) accountId); account = userAccountsApi.getAccountById((int) accountId);
} }
else { else {
@ -590,7 +569,6 @@ public class LoginActivity extends BaseActivity {
}); });
} }
private void loadDefaults() { private void loadDefaults() {
if(tinyDB.getString("loginType").equals(LoginType.BASIC.name().toLowerCase())) { if(tinyDB.getString("loginType").equals(LoginType.BASIC.name().toLowerCase())) {
@ -634,4 +612,6 @@ public class LoginActivity extends BaseActivity {
loginButton.setEnabled(true); loginButton.setEnabled(true);
} }
private enum LoginType {BASIC, TOKEN}
} }

View File

@ -34,26 +34,8 @@ import org.mian.gitnex.database.api.BaseApi;
import org.mian.gitnex.database.api.UserAccountsApi; import org.mian.gitnex.database.api.UserAccountsApi;
import org.mian.gitnex.database.models.UserAccount; import org.mian.gitnex.database.models.UserAccount;
import org.mian.gitnex.databinding.ActivityMainBinding; import org.mian.gitnex.databinding.ActivityMainBinding;
import org.mian.gitnex.fragments.AdministrationFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.BottomSheetDraftsFragment; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.fragments.BottomSheetMyIssuesFilterFragment;
import org.mian.gitnex.fragments.DraftsFragment;
import org.mian.gitnex.fragments.ExploreFragment;
import org.mian.gitnex.fragments.MostVisitedReposFragment;
import org.mian.gitnex.fragments.MyIssuesFragment;
import org.mian.gitnex.fragments.MyProfileFragment;
import org.mian.gitnex.fragments.MyRepositoriesFragment;
import org.mian.gitnex.fragments.NotificationsFragment;
import org.mian.gitnex.fragments.OrganizationsFragment;
import org.mian.gitnex.fragments.RepositoriesFragment;
import org.mian.gitnex.fragments.SettingsFragment;
import org.mian.gitnex.fragments.StarredRepositoriesFragment;
import org.mian.gitnex.helpers.AlertDialogs;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.ChangeLog;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import org.mian.gitnex.structs.FragmentRefreshListener; import org.mian.gitnex.structs.FragmentRefreshListener;
import java.util.ArrayList; import java.util.ArrayList;
@ -98,9 +80,7 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
Handler handler = new Handler(); Handler handler = new Handler();
// DO NOT MOVE // DO NOT MOVE
if(mainIntent.hasExtra("switchAccountId") && if(mainIntent.hasExtra("switchAccountId") && AppUtil.switchToAccount(ctx, BaseApi.getInstance(ctx, UserAccountsApi.class).getAccountById(mainIntent.getIntExtra("switchAccountId", 0)))) {
AppUtil.switchToAccount(ctx, BaseApi.getInstance(ctx, UserAccountsApi.class)
.getAccountById(mainIntent.getIntExtra("switchAccountId", 0)))) {
mainIntent.removeExtra("switchAccountId"); mainIntent.removeExtra("switchAccountId");
recreate(); recreate();
@ -225,10 +205,10 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
int avatarRadius = AppUtil.getPixelsFromDensity(ctx, 3); int avatarRadius = AppUtil.getPixelsFromDensity(ctx, 3);
PicassoService.getInstance(ctx).get().load(userAvatarNav).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(avatarRadius, 0)).resize(160, 160).centerCrop().into(userAvatar); PicassoService.getInstance(ctx).get().load(userAvatarNav).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(avatarRadius, 0)).resize(160, 160).centerCrop()
.into(userAvatar);
PicassoService.getInstance(ctx).get().load(userAvatarNav).transform(new BlurTransformation(ctx)) PicassoService.getInstance(ctx).get().load(userAvatarNav).transform(new BlurTransformation(ctx)).into(userAvatarBackground, new com.squareup.picasso.Callback() {
.into(userAvatarBackground, new com.squareup.picasso.Callback() {
@Override @Override
public void onSuccess() { public void onSuccess() {
@ -264,7 +244,8 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
if(getAccount().getUserInfo() != null) { if(getAccount().getUserInfo() != null) {
navigationView.getMenu().findItem(R.id.nav_administration).setVisible(getAccount().getUserInfo().isIsAdmin()); navigationView.getMenu().findItem(R.id.nav_administration).setVisible(getAccount().getUserInfo().isIsAdmin());
} else { }
else {
// hide first // hide first
navigationView.getMenu().findItem(R.id.nav_administration).setVisible(false); navigationView.getMenu().findItem(R.id.nav_administration).setVisible(false);
} }
@ -275,10 +256,12 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
} }
@Override @Override
public void onDrawerClosed(@NonNull View drawerView) {} public void onDrawerClosed(@NonNull View drawerView) {
}
@Override @Override
public void onDrawerStateChanged(int newState) {} public void onDrawerStateChanged(int newState) {
}
}); });
@ -480,17 +463,13 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
if(frag != null) { if(frag != null) {
new MaterialAlertDialogBuilder(ctx) new MaterialAlertDialogBuilder(ctx).setTitle(R.string.deleteAllDrafts).setCancelable(false).setMessage(R.string.deleteAllDraftsDialogMessage)
.setTitle(R.string.deleteAllDrafts)
.setCancelable(false)
.setMessage(R.string.deleteAllDraftsDialogMessage)
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> { .setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
frag.deleteAllDrafts(currentActiveAccountId); frag.deleteAllDrafts(currentActiveAccountId);
dialog.dismiss(); dialog.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null).show();
.setNeutralButton(R.string.cancelButton, null).show();
} }
else { else {
@ -761,6 +740,12 @@ public class MainActivity extends BaseActivity implements NavigationView.OnNavig
} }
// My issues interface // My issues interface
public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListenerMyIssues; } public FragmentRefreshListener getFragmentRefreshListener() {
public void setFragmentRefreshListenerMyIssues(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerMyIssues = fragmentRefreshListener; } return fragmentRefreshListenerMyIssues;
}
public void setFragmentRefreshListenerMyIssues(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerMyIssues = fragmentRefreshListener;
}
} }

View File

@ -34,6 +34,7 @@ public class MergePullRequestActivity extends BaseActivity {
private IssueContext issue; private IssueContext issue;
private ActivityMergePullRequestBinding viewBinding; private ActivityMergePullRequestBinding viewBinding;
private String Do; private String Do;
private final View.OnClickListener mergePullRequest = v -> processMergePullRequest();
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@Override @Override
@ -132,8 +133,6 @@ public class MergePullRequestActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private final View.OnClickListener mergePullRequest = v -> processMergePullRequest();
private void processMergePullRequest() { private void processMergePullRequest() {
String mergePRDesc = Objects.requireNonNull(viewBinding.mergeDescription.getText()).toString(); String mergePRDesc = Objects.requireNonNull(viewBinding.mergeDescription.getText()).toString();
@ -200,8 +199,7 @@ public class MergePullRequestActivity extends BaseActivity {
PullRequestActions.deleteHeadBranch(ctx, repoOwner, repoName, issue.getPullRequest().getHead().getRef(), false); PullRequestActions.deleteHeadBranch(ctx, repoOwner, repoName, issue.getPullRequest().getHead().getRef(), false);
} }
else { else {
PullRequestActions.deleteHeadBranch(ctx, issue.getRepository().getOwner(), issue.getRepository().getName(), PullRequestActions.deleteHeadBranch(ctx, issue.getRepository().getOwner(), issue.getRepository().getName(), issue.getPullRequest().getHead().getRef(), false);
issue.getPullRequest().getHead().getRef(), false);
} }
} }
@ -259,4 +257,5 @@ public class MergePullRequestActivity extends BaseActivity {
super.onResume(); super.onResume();
issue.getRepository().checkAccountSwitch(this); issue.getRepository().checkAccountSwitch(this);
} }
} }

View File

@ -34,6 +34,7 @@ public class MyProfileEmailActivity extends BaseActivity {
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private EditText userEmail; private EditText userEmail;
private Button addEmailButton; private Button addEmailButton;
private final View.OnClickListener addEmailListener = v -> processAddNewEmail();
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -61,15 +62,14 @@ public class MyProfileEmailActivity extends BaseActivity {
if(!connToInternet) { if(!connToInternet) {
disableProcessButton(); disableProcessButton();
} else { }
else {
addEmailButton.setOnClickListener(addEmailListener); addEmailButton.setOnClickListener(addEmailListener);
} }
} }
private final View.OnClickListener addEmailListener = v -> processAddNewEmail();
private void processAddNewEmail() { private void processAddNewEmail() {
boolean connToInternet = AppUtil.hasNetworkConnection(appCtx); boolean connToInternet = AppUtil.hasNetworkConnection(appCtx);
@ -104,9 +104,7 @@ public class MyProfileEmailActivity extends BaseActivity {
CreateEmailOption addEmailFunc = new CreateEmailOption(); CreateEmailOption addEmailFunc = new CreateEmailOption();
addEmailFunc.setEmails(newUserEmail); addEmailFunc.setEmails(newUserEmail);
Call<List<Email>> call = RetrofitClient Call<List<Email>> call = RetrofitClient.getApiInterface(ctx).userAddEmail(addEmailFunc);
.getApiInterface(ctx)
.userAddEmail(addEmailFunc);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {

View File

@ -3,11 +3,7 @@ package org.mian.gitnex.activities;
import android.content.Intent; import android.content.Intent;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.view.Menu; import android.view.*;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar; import androidx.appcompat.widget.Toolbar;
@ -20,12 +16,7 @@ import org.gitnex.tea4j.v2.models.OrganizationPermissions;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetOrganizationFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.MembersByOrgFragment;
import org.mian.gitnex.fragments.OrganizationInfoFragment;
import org.mian.gitnex.fragments.OrganizationLabelsFragment;
import org.mian.gitnex.fragments.RepositoriesByOrgFragment;
import org.mian.gitnex.fragments.TeamsByOrgFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
import java.util.Objects; import java.util.Objects;
@ -62,8 +53,7 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
checkIsMember(); checkIsMember();
if(getAccount().requiresVersion("1.16.0")) { if(getAccount().requiresVersion("1.16.0")) {
RetrofitClient.getApiInterface(this) RetrofitClient.getApiInterface(this).orgGetUserPermissions(getAccount().getAccount().getUserName(), orgName).enqueue(new Callback<>() {
.orgGetUserPermissions(getAccount().getAccount().getUserName(), orgName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<OrganizationPermissions> call, @NonNull Response<OrganizationPermissions> response) { public void onResponse(@NonNull Call<OrganizationPermissions> call, @NonNull Response<OrganizationPermissions> response) {
@ -82,7 +72,8 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
permissions = null; permissions = null;
} }
}); });
} else { }
else {
permissions = null; permissions = null;
} }
} }
@ -180,9 +171,7 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
@Override @Override
public void onButtonClicked(String text) { public void onButtonClicked(String text) {
String url = UrlBuilder.fromString(getAccount().getAccount().getInstanceUrl()) String url = UrlBuilder.fromString(getAccount().getAccount().getInstanceUrl()).withPath("/").toString();
.withPath("/")
.toString();
url = url + getIntent().getStringExtra("orgName"); url = url + getIntent().getStringExtra("orgName");
switch(text) { switch(text) {
@ -245,7 +234,8 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
if(isMember) { if(isMember) {
return TeamsByOrgFragment.newInstance(orgName, permissions); return TeamsByOrgFragment.newInstance(orgName, permissions);
} else { }
else {
return MembersByOrgFragment.newInstance(orgName); return MembersByOrgFragment.newInstance(orgName);
} }
case 4: // members case 4: // members
@ -261,9 +251,12 @@ public class OrganizationDetailActivity extends BaseActivity implements BottomSh
public int getCount() { public int getCount() {
if(isMember) { if(isMember) {
return 5; return 5;
} else { }
else {
return 4; return 4;
} }
} }
} }
} }

View File

@ -53,6 +53,7 @@ public class OrganizationTeamInfoActivity extends BaseActivity implements Bottom
binding.close.setOnClickListener(view -> finish()); binding.close.setOnClickListener(view -> finish());
binding.pager.setOffscreenPageLimit(1); binding.pager.setOffscreenPageLimit(1);
binding.pager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) { binding.pager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
@NonNull @NonNull
@Override @Override
public Fragment createFragment(int position) { public Fragment createFragment(int position) {
@ -129,7 +130,8 @@ public class OrganizationTeamInfoActivity extends BaseActivity implements Bottom
Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamMemberActivity.class); Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamMemberActivity.class);
intent.putExtra("teamId", team.getId()); intent.putExtra("teamId", team.getId());
startActivity(intent); startActivity(intent);
} else if("newRepo".equals(text)) { }
else if("newRepo".equals(text)) {
Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamRepoActivity.class); Intent intent = new Intent(OrganizationTeamInfoActivity.this, AddNewTeamRepoActivity.class);
intent.putExtra("teamId", team.getId()); intent.putExtra("teamId", team.getId());
intent.putExtra("teamName", team.getName()); intent.putExtra("teamName", team.getName());
@ -137,4 +139,5 @@ public class OrganizationTeamInfoActivity extends BaseActivity implements Bottom
startActivity(intent); startActivity(intent);
} }
} }
} }

View File

@ -19,12 +19,7 @@ import com.google.android.material.tabs.TabLayoutMediator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetUserProfileFragment; import org.mian.gitnex.fragments.BottomSheetUserProfileFragment;
import org.mian.gitnex.fragments.profile.DetailFragment; import org.mian.gitnex.fragments.profile.*;
import org.mian.gitnex.fragments.profile.FollowersFragment;
import org.mian.gitnex.fragments.profile.FollowingFragment;
import org.mian.gitnex.fragments.profile.OrganizationsFragment;
import org.mian.gitnex.fragments.profile.RepositoriesFragment;
import org.mian.gitnex.fragments.profile.StarredRepositoriesFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.BottomSheetListener; import org.mian.gitnex.structs.BottomSheetListener;
@ -74,7 +69,8 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
viewPager.setAdapter(new ViewPagerAdapter(this)); viewPager.setAdapter(new ViewPagerAdapter(this));
String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.navRepos), ctx.getResources().getString(R.string.navStarredRepos), ctx.getResources().getString(R.string.navOrg), ctx.getResources().getString(R.string.profileTabFollowers), ctx.getResources().getString(R.string.profileTabFollowing)}; String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.navRepos), ctx.getResources().getString(R.string.navStarredRepos),
ctx.getResources().getString(R.string.navOrg), ctx.getResources().getString(R.string.profileTabFollowers), ctx.getResources().getString(R.string.profileTabFollowing)};
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach(); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach();
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0); ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
@ -149,7 +145,8 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
else { else {
Toasty.success(ProfileActivity.this, String.format(getString(R.string.unfollowedUser), username)); Toasty.success(ProfileActivity.this, String.format(getString(R.string.unfollowedUser), username));
} }
} else { }
else {
if(following) { if(following) {
Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed)); Toasty.error(ProfileActivity.this, getString(R.string.unfollowingFailed));
} }
@ -171,36 +168,6 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
}); });
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) { super(fa); }
@NonNull
@Override
public Fragment createFragment(int position) {
switch(position) {
case 0: // detail
return DetailFragment.newInstance(username);
case 1: // repos
return RepositoriesFragment.newInstance(username);
case 2: // starred repos
return StarredRepositoriesFragment.newInstance(username);
case 3: // organizations
return OrganizationsFragment.newInstance(username);
case 4: // followers
return FollowersFragment.newInstance(username);
case 5: // following
return FollowingFragment.newInstance(username);
}
return null;
}
@Override
public int getItemCount() {
return 6;
}
}
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
@ -227,4 +194,37 @@ public class ProfileActivity extends BaseActivity implements BottomSheetListener
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch(position) {
case 0: // detail
return DetailFragment.newInstance(username);
case 1: // repos
return RepositoriesFragment.newInstance(username);
case 2: // starred repos
return StarredRepositoriesFragment.newInstance(username);
case 3: // organizations
return OrganizationsFragment.newInstance(username);
case 4: // followers
return FollowersFragment.newInstance(username);
case 5: // following
return FollowingFragment.newInstance(username);
}
return null;
}
@Override
public int getItemCount() {
return 6;
}
}
} }

View File

@ -6,12 +6,7 @@ import android.content.Intent;
import android.content.res.ColorStateList; import android.content.res.ColorStateList;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.*;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.ActivityResultLauncher;
@ -26,27 +21,10 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.progressindicator.LinearProgressIndicator; import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator; import com.google.android.material.tabs.TabLayoutMediator;
import org.gitnex.tea4j.v2.models.Branch; import org.gitnex.tea4j.v2.models.*;
import org.gitnex.tea4j.v2.models.Milestone;
import org.gitnex.tea4j.v2.models.Organization;
import org.gitnex.tea4j.v2.models.Repository;
import org.gitnex.tea4j.v2.models.WatchInfo;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetIssuesFilterFragment; import org.mian.gitnex.fragments.*;
import org.mian.gitnex.fragments.BottomSheetMilestonesFilterFragment;
import org.mian.gitnex.fragments.BottomSheetPullRequestFilterFragment;
import org.mian.gitnex.fragments.BottomSheetReleasesTagsFragment;
import org.mian.gitnex.fragments.BottomSheetRepoFragment;
import org.mian.gitnex.fragments.CollaboratorsFragment;
import org.mian.gitnex.fragments.FilesFragment;
import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.fragments.LabelsFragment;
import org.mian.gitnex.fragments.MilestonesFragment;
import org.mian.gitnex.fragments.PullRequestsFragment;
import org.mian.gitnex.fragments.ReleasesFragment;
import org.mian.gitnex.fragments.RepoInfoFragment;
import org.mian.gitnex.fragments.WikiFragment;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Toasty; import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
@ -65,63 +43,8 @@ import retrofit2.Response;
public class RepoDetailActivity extends BaseActivity implements BottomSheetListener { public class RepoDetailActivity extends BaseActivity implements BottomSheetListener {
private TextView textViewBadgeIssue;
private TextView textViewBadgePull;
private TextView textViewBadgeRelease;
private Typeface myTypeface;
private FragmentRefreshListener fragmentRefreshListener;
private FragmentRefreshListener fragmentRefreshListenerPr;
private FragmentRefreshListener fragmentRefreshListenerMilestone;
private FragmentRefreshListener fragmentRefreshListenerFiles;
private FragmentRefreshListener fragmentRefreshListenerFilterIssuesByMilestone;
private FragmentRefreshListener fragmentRefreshListenerReleases;
public ViewPager2 viewPager;
public RepositoryContext repository;
public static boolean updateRepo = false; public static boolean updateRepo = false;
private Dialog progressDialog; private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
private Intent intentWiki;
private final ActivityResultLauncher<Intent> createReleaseLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("updateReleases", false)) {
if(fragmentRefreshListenerReleases != null) fragmentRefreshListenerReleases.onRefresh(null);
repository.removeRepository();
getRepoInfo(repository.getOwner(), repository.getName());
}
}
});
private final ActivityResultLauncher<Intent> createMilestoneLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("milestoneCreated", false)) {
if(fragmentRefreshListenerMilestone != null) fragmentRefreshListenerMilestone.onRefresh(repository.getMilestoneState().toString());
}
}
});
private final ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("fileModified", false)) {
if(fragmentRefreshListenerFiles != null) fragmentRefreshListenerFiles.onRefresh(repository.getBranchRef());
}
}
});
private final ActivityResultLauncher<Intent> settingsLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
if(result.getResultCode() == 200) { if(result.getResultCode() == 200) {
assert result.getData() != null; assert result.getData() != null;
if(result.getData().getBooleanExtra("nameChanged", false)) { if(result.getData().getBooleanExtra("nameChanged", false)) {
@ -129,6 +52,53 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
} }
}); });
public ViewPager2 viewPager;
public RepositoryContext repository;
private TextView textViewBadgeIssue;
private TextView textViewBadgePull;
private TextView textViewBadgeRelease;
private Typeface myTypeface;
private FragmentRefreshListener fragmentRefreshListener;
private FragmentRefreshListener fragmentRefreshListenerPr;
private FragmentRefreshListener fragmentRefreshListenerMilestone;
private final ActivityResultLauncher<Intent> createMilestoneLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("milestoneCreated", false)) {
if(fragmentRefreshListenerMilestone != null) {
fragmentRefreshListenerMilestone.onRefresh(repository.getMilestoneState().toString());
}
}
}
});
private FragmentRefreshListener fragmentRefreshListenerFiles;
private final ActivityResultLauncher<Intent> editFileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 200) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("fileModified", false)) {
if(fragmentRefreshListenerFiles != null) {
fragmentRefreshListenerFiles.onRefresh(repository.getBranchRef());
}
}
}
});
private FragmentRefreshListener fragmentRefreshListenerFilterIssuesByMilestone;
private FragmentRefreshListener fragmentRefreshListenerReleases;
private Dialog progressDialog;
private final ActivityResultLauncher<Intent> createReleaseLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == 201) {
assert result.getData() != null;
if(result.getData().getBooleanExtra("updateReleases", false)) {
if(fragmentRefreshListenerReleases != null) {
fragmentRefreshListenerReleases.onRefresh(null);
}
repository.removeRepository();
getRepoInfo(repository.getOwner(), repository.getName());
}
}
});
private MaterialAlertDialogBuilder materialAlertDialogBuilder;
private Intent intentWiki;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -204,7 +174,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
finish(); finish();
} }
}); });
} else { }
else {
finish(); finish();
} }
return true; return true;
@ -389,9 +360,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
progressDialog.setContentView(R.layout.custom_progress_loader); progressDialog.setContentView(R.layout.custom_progress_loader);
progressDialog.show(); progressDialog.show();
Call<List<Milestone>> call = RetrofitClient Call<List<Milestone>> call = RetrofitClient.getApiInterface(ctx).issueGetMilestonesList(repository.getOwner(), repository.getName(), "open", null, 1, 50);
.getApiInterface(ctx)
.issueGetMilestonesList(repository.getOwner(), repository.getName(), "open", null, 1, 50);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -419,8 +388,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
} }
materialAlertDialogBuilder.setTitle(R.string.selectMilestone) materialAlertDialogBuilder.setTitle(R.string.selectMilestone).setSingleChoiceItems(milestonesList.toArray(new String[0]), selectedMilestone, (dialogInterface, i) -> {
.setSingleChoiceItems(milestonesList.toArray(new String[0]), selectedMilestone, (dialogInterface, i) -> {
repository.setIssueMilestoneFilterName(milestonesList.get(i)); repository.setIssueMilestoneFilterName(milestonesList.get(i));
@ -428,8 +396,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
getFragmentRefreshListenerFilterIssuesByMilestone().onRefresh(milestonesList.get(i)); getFragmentRefreshListenerFilterIssuesByMilestone().onRefresh(milestonesList.get(i));
} }
dialogInterface.dismiss(); dialogInterface.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null);
.setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
} }
@ -457,9 +424,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
progressDialog.setContentView(R.layout.custom_progress_loader); progressDialog.setContentView(R.layout.custom_progress_loader);
progressDialog.show(); progressDialog.show();
Call<List<Branch>> call = RetrofitClient Call<List<Branch>> call = RetrofitClient.getApiInterface(ctx).repoListBranches(repository.getOwner(), repository.getName(), null, null);
.getApiInterface(ctx)
.repoListBranches(repository.getOwner(), repository.getName(), null, null);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -483,8 +448,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
} }
materialAlertDialogBuilder.setTitle(R.string.pageTitleChooseBranch) materialAlertDialogBuilder.setTitle(R.string.pageTitleChooseBranch).setSingleChoiceItems(branchesList.toArray(new String[0]), selectedBranch, (dialogInterface, i) -> {
.setSingleChoiceItems(branchesList.toArray(new String[0]), selectedBranch, (dialogInterface, i) -> {
repository.setBranchRef(branchesList.get(i)); repository.setBranchRef(branchesList.get(i));
@ -492,8 +456,7 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
getFragmentRefreshListenerFiles().onRefresh(branchesList.get(i)); getFragmentRefreshListenerFiles().onRefresh(branchesList.get(i));
} }
dialogInterface.dismiss(); dialogInterface.dismiss();
}) }).setNeutralButton(R.string.cancelButton, null);
.setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
} }
@ -505,49 +468,6 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
}); });
} }
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) { super(fa); }
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = null;
switch(position) {
case 0: // Repository details
return RepoInfoFragment.newInstance(repository);
case 1: // Files
return FilesFragment.newInstance(repository);
case 2: // Issues
fragment = IssuesFragment.newInstance(repository);
break;
case 3: // Pull requests
fragment = PullRequestsFragment.newInstance(repository);
break;
case 4: // Releases
return ReleasesFragment.newInstance(repository);
case 5: // Wiki
return WikiFragment.newInstance(repository);
case 6: // Milestones
fragment = MilestonesFragment.newInstance(repository);
break;
case 7: // Labels
return LabelsFragment.newInstance(repository);
case 8: // Collaborators
return CollaboratorsFragment.newInstance(repository);
}
assert fragment != null;
return fragment;
}
@Override
public int getItemCount() {
return 9;
}
}
private void getRepoInfo(final String owner, String repo) { private void getRepoInfo(final String owner, String repo) {
LinearProgressIndicator loading = findViewById(R.id.loadingIndicator); LinearProgressIndicator loading = findViewById(R.id.loadingIndicator);
@ -592,7 +512,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
ImageView repoTypeToolbar = findViewById(R.id.repoTypeToolbar); ImageView repoTypeToolbar = findViewById(R.id.repoTypeToolbar);
if(repository.getRepository().isPrivate()) { if(repository.getRepository().isPrivate()) {
repoTypeToolbar.setVisibility(View.VISIBLE); repoTypeToolbar.setVisibility(View.VISIBLE);
} else { }
else {
repoTypeToolbar.setVisibility(View.GONE); repoTypeToolbar.setVisibility(View.GONE);
} }
@ -605,7 +526,9 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
viewPager.setAdapter(new ViewPagerAdapter(this)); viewPager.setAdapter(new ViewPagerAdapter(this));
String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.tabTextFiles), ctx.getResources().getString(R.string.pageTitleIssues), ctx.getResources().getString(R.string.tabPullRequests), ctx.getResources().getString(R.string.tabTextReleases), ctx.getResources().getString(R.string.wiki), ctx.getResources().getString(R.string.tabTextMl), ctx.getResources().getString(R.string.newIssueLabelsTitle), ctx.getResources().getString(R.string.tabTextCollaborators)}; String[] tabTitles = {ctx.getResources().getString(R.string.tabTextInfo), ctx.getResources().getString(R.string.tabTextFiles), ctx.getResources().getString(R.string.pageTitleIssues),
ctx.getResources().getString(R.string.tabPullRequests), ctx.getResources().getString(R.string.tabTextReleases), ctx.getResources().getString(R.string.wiki),
ctx.getResources().getString(R.string.tabTextMl), ctx.getResources().getString(R.string.newIssueLabelsTitle), ctx.getResources().getString(R.string.tabTextCollaborators)};
new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach(); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(tabTitles[position])).attach();
ViewGroup viewGroup = (ViewGroup) tabLayout.getChildAt(0); ViewGroup viewGroup = (ViewGroup) tabLayout.getChildAt(0);
@ -658,7 +581,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openIssueTabView = Objects.requireNonNull(tabOpenIssues.getCustomView()).findViewById(R.id.counterBadgeIssueText); TextView openIssueTabView = Objects.requireNonNull(tabOpenIssues.getCustomView()).findViewById(R.id.counterBadgeIssueText);
openIssueTabView.setTextColor(textColor); openIssueTabView.setTextColor(textColor);
} else { }
else {
textViewBadgeIssue.setVisibility(View.GONE); textViewBadgeIssue.setVisibility(View.GONE);
} }
@ -674,7 +598,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openPullTabView = Objects.requireNonNull(tabOpenPulls.getCustomView()).findViewById(R.id.counterBadgePullText); TextView openPullTabView = Objects.requireNonNull(tabOpenPulls.getCustomView()).findViewById(R.id.counterBadgePullText);
openPullTabView.setTextColor(textColor); openPullTabView.setTextColor(textColor);
} else { }
else {
textViewBadgePull.setVisibility(View.GONE); textViewBadgePull.setVisibility(View.GONE);
} }
@ -690,7 +615,8 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
TextView openReleaseTabView = Objects.requireNonNull(tabOpenRelease.getCustomView()).findViewById(R.id.counterBadgeReleaseText); TextView openReleaseTabView = Objects.requireNonNull(tabOpenRelease.getCustomView()).findViewById(R.id.counterBadgeReleaseText);
openReleaseTabView.setTextColor(textColor); openReleaseTabView.setTextColor(textColor);
} else { }
else {
textViewBadgeRelease.setVisibility(View.GONE); textViewBadgeRelease.setVisibility(View.GONE);
} }
} }
@ -833,33 +759,104 @@ public class RepoDetailActivity extends BaseActivity implements BottomSheetListe
} }
// Issues milestone filter interface // Issues milestone filter interface
public FragmentRefreshListener getFragmentRefreshListenerFilterIssuesByMilestone() { return fragmentRefreshListenerFilterIssuesByMilestone; } public FragmentRefreshListener getFragmentRefreshListenerFilterIssuesByMilestone() {
return fragmentRefreshListenerFilterIssuesByMilestone;
}
public void setFragmentRefreshListenerFilterIssuesByMilestone(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerFilterIssuesByMilestone = fragmentRefreshListener; } public void setFragmentRefreshListenerFilterIssuesByMilestone(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerFilterIssuesByMilestone = fragmentRefreshListener;
}
// Issues interface // Issues interface
public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListener; } public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListener = fragmentRefreshListener; } public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
// Pull request interface // Pull request interface
public FragmentRefreshListener getFragmentRefreshListenerPr() { return fragmentRefreshListenerPr; } public FragmentRefreshListener getFragmentRefreshListenerPr() {
return fragmentRefreshListenerPr;
}
public void setFragmentRefreshListenerPr(FragmentRefreshListener fragmentRefreshListenerPr) { this.fragmentRefreshListenerPr = fragmentRefreshListenerPr; } public void setFragmentRefreshListenerPr(FragmentRefreshListener fragmentRefreshListenerPr) {
this.fragmentRefreshListenerPr = fragmentRefreshListenerPr;
}
// Milestones interface // Milestones interface
public FragmentRefreshListener getFragmentRefreshListenerMilestone() { return fragmentRefreshListenerMilestone; } public FragmentRefreshListener getFragmentRefreshListenerMilestone() {
return fragmentRefreshListenerMilestone;
}
public void setFragmentRefreshListenerMilestone(FragmentRefreshListener fragmentRefreshListenerMilestone) { this.fragmentRefreshListenerMilestone = fragmentRefreshListenerMilestone; } public void setFragmentRefreshListenerMilestone(FragmentRefreshListener fragmentRefreshListenerMilestone) {
this.fragmentRefreshListenerMilestone = fragmentRefreshListenerMilestone;
}
// Files interface // Files interface
public FragmentRefreshListener getFragmentRefreshListenerFiles() { return fragmentRefreshListenerFiles; } public FragmentRefreshListener getFragmentRefreshListenerFiles() {
return fragmentRefreshListenerFiles;
}
public void setFragmentRefreshListenerFiles(FragmentRefreshListener fragmentRefreshListenerFiles) { this.fragmentRefreshListenerFiles = fragmentRefreshListenerFiles; } public void setFragmentRefreshListenerFiles(FragmentRefreshListener fragmentRefreshListenerFiles) {
this.fragmentRefreshListenerFiles = fragmentRefreshListenerFiles;
}
//Releases interface //Releases interface
public FragmentRefreshListener getFragmentRefreshListenerReleases() { return fragmentRefreshListenerReleases; } public FragmentRefreshListener getFragmentRefreshListenerReleases() {
return fragmentRefreshListenerReleases;
}
public void setFragmentRefreshListenerReleases(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListenerReleases = fragmentRefreshListener;
}
public class ViewPagerAdapter extends FragmentStateAdapter {
public ViewPagerAdapter(@NonNull FragmentActivity fa) {
super(fa);
}
@NonNull
@Override
public Fragment createFragment(int position) {
Fragment fragment = null;
switch(position) {
case 0: // Repository details
return RepoInfoFragment.newInstance(repository);
case 1: // Files
return FilesFragment.newInstance(repository);
case 2: // Issues
fragment = IssuesFragment.newInstance(repository);
break;
case 3: // Pull requests
fragment = PullRequestsFragment.newInstance(repository);
break;
case 4: // Releases
return ReleasesFragment.newInstance(repository);
case 5: // Wiki
return WikiFragment.newInstance(repository);
case 6: // Milestones
fragment = MilestonesFragment.newInstance(repository);
break;
case 7: // Labels
return LabelsFragment.newInstance(repository);
case 8: // Collaborators
return CollaboratorsFragment.newInstance(repository);
}
assert fragment != null;
return fragment;
}
@Override
public int getItemCount() {
return 9;
}
}
public void setFragmentRefreshListenerReleases(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListenerReleases = fragmentRefreshListener; }
} }

View File

@ -39,9 +39,9 @@ import retrofit2.Response;
public class RepoForksActivity extends BaseActivity { public class RepoForksActivity extends BaseActivity {
private final String TAG = "RepositoryForks";
private TextView noData; private TextView noData;
private ProgressBar progressBar; private ProgressBar progressBar;
private final String TAG = "RepositoryForks";
private int resultLimit; private int resultLimit;
private int pageSize = 1; private int pageSize = 1;
@ -113,9 +113,7 @@ public class RepoForksActivity extends BaseActivity {
private void loadInitial(String repoOwner, String repoName, int pageSize, int resultLimit) { private void loadInitial(String repoOwner, String repoName, int pageSize, int resultLimit) {
Call<List<Repository>> call = RetrofitClient Call<List<Repository>> call = RetrofitClient.getApiInterface(ctx).listForks(repoOwner, repoName, pageSize, resultLimit);
.getApiInterface(ctx)
.listForks(repoOwner, repoName, pageSize, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -157,9 +155,7 @@ public class RepoForksActivity extends BaseActivity {
progressLoadMore.setVisibility(View.VISIBLE); progressLoadMore.setVisibility(View.VISIBLE);
Call<List<Repository>> call = RetrofitClient Call<List<Repository>> call = RetrofitClient.getApiInterface(ctx).listForks(repoOwner, repoName, page, resultLimit);
.getApiInterface(ctx)
.listForks(repoOwner, repoName, page, resultLimit);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -230,8 +226,7 @@ public class RepoForksActivity extends BaseActivity {
List<Repository> userRepositories = new ArrayList<>(); List<Repository> userRepositories = new ArrayList<>();
for(Repository d : forksList) { for(Repository d : forksList) {
if(d.getOwner().getLogin().contains(text) || d.getName().toLowerCase().contains(text) || if(d.getOwner().getLogin().contains(text) || d.getName().toLowerCase().contains(text) || d.getDescription().toLowerCase().contains(text)) {
d.getDescription().toLowerCase().contains(text)) {
userRepositories.add(d); userRepositories.add(d);
} }
@ -245,4 +240,5 @@ public class RepoForksActivity extends BaseActivity {
super.onResume(); super.onResume();
repository.checkAccountSwitch(this); repository.checkAccountSwitch(this);
} }
} }

View File

@ -116,9 +116,7 @@ public class RepositorySettingsActivity extends BaseActivity {
TransferRepoOption repositoryTransfer = new TransferRepoOption(); TransferRepoOption repositoryTransfer = new TransferRepoOption();
repositoryTransfer.setNewOwner(newOwner); repositoryTransfer.setNewOwner(newOwner);
Call<Repository> transferCall = RetrofitClient Call<Repository> transferCall = RetrofitClient.getApiInterface(ctx).repoTransfer(repositoryTransfer, repository.getOwner(), repository.getName());
.getApiInterface(ctx)
.repoTransfer(repositoryTransfer, repository.getOwner(), repository.getName());
transferCall.enqueue(new Callback<Repository>() { transferCall.enqueue(new Callback<Repository>() {
@ -187,9 +185,7 @@ public class RepositorySettingsActivity extends BaseActivity {
private void deleteRepository() { private void deleteRepository() {
Call<Void> deleteCall = RetrofitClient Call<Void> deleteCall = RetrofitClient.getApiInterface(ctx).repoDelete(repository.getOwner(), repository.getName());
.getApiInterface(ctx)
.repoDelete(repository.getOwner(), repository.getName());
deleteCall.enqueue(new Callback<Void>() { deleteCall.enqueue(new Callback<Void>() {
@ -275,22 +271,17 @@ public class RepositorySettingsActivity extends BaseActivity {
propBinding.repoEnableSquash.setChecked(repoInfo.isAllowSquashMerge()); propBinding.repoEnableSquash.setChecked(repoInfo.isAllowSquashMerge());
propBinding.repoEnableForceMerge.setChecked(repoInfo.isAllowRebaseExplicit()); propBinding.repoEnableForceMerge.setChecked(repoInfo.isAllowRebaseExplicit());
propBinding.save.setOnClickListener(saveProperties -> saveRepositoryProperties(String.valueOf(propBinding.repoName.getText()), propBinding.save.setOnClickListener(
String.valueOf(propBinding.repoWebsite.getText()), saveProperties -> saveRepositoryProperties(String.valueOf(propBinding.repoName.getText()), String.valueOf(propBinding.repoWebsite.getText()), String.valueOf(propBinding.repoDescription.getText()),
String.valueOf(propBinding.repoDescription.getText()), propBinding.repoPrivate.isChecked(), propBinding.repoAsTemplate.isChecked(), propBinding.repoEnableIssues.isChecked(), propBinding.repoEnableWiki.isChecked(), propBinding.repoEnablePr.isChecked(),
propBinding.repoPrivate.isChecked(), propBinding.repoAsTemplate.isChecked(), propBinding.repoEnableTimer.isChecked(), propBinding.repoEnableMerge.isChecked(), propBinding.repoEnableRebase.isChecked(), propBinding.repoEnableSquash.isChecked(),
propBinding.repoEnableIssues.isChecked(), propBinding.repoEnableWiki.isChecked(), propBinding.repoEnableForceMerge.isChecked()));
propBinding.repoEnablePr.isChecked(), propBinding.repoEnableTimer.isChecked(),
propBinding.repoEnableMerge.isChecked(), propBinding.repoEnableRebase.isChecked(),
propBinding.repoEnableSquash.isChecked(), propBinding.repoEnableForceMerge.isChecked()));
dialogRepo = materialAlertDialogBuilder.show(); dialogRepo = materialAlertDialogBuilder.show();
} }
private void saveRepositoryProperties(String repoName, String repoWebsite, String repoDescription, private void saveRepositoryProperties(String repoName, String repoWebsite, String repoDescription, boolean repoPrivate, boolean repoAsTemplate, boolean repoEnableIssues, boolean repoEnableWiki, boolean repoEnablePr,
boolean repoPrivate, boolean repoAsTemplate, boolean repoEnableIssues, boolean repoEnableWiki, boolean repoEnableTimer, boolean repoEnableMerge, boolean repoEnableRebase, boolean repoEnableSquash, boolean repoEnableForceMerge) {
boolean repoEnablePr, boolean repoEnableTimer, boolean repoEnableMerge, boolean repoEnableRebase,
boolean repoEnableSquash, boolean repoEnableForceMerge) {
EditRepoOption repoProps = new EditRepoOption(); EditRepoOption repoProps = new EditRepoOption();
repoProps.setName(repoName); repoProps.setName(repoName);
@ -307,9 +298,7 @@ public class RepositorySettingsActivity extends BaseActivity {
repoProps.setAllowSquashMerge(repoEnableSquash); repoProps.setAllowSquashMerge(repoEnableSquash);
repoProps.setAllowRebaseExplicit(repoEnableForceMerge); repoProps.setAllowRebaseExplicit(repoEnableForceMerge);
Call<Repository> propsCall = RetrofitClient Call<Repository> propsCall = RetrofitClient.getApiInterface(ctx).repoEdit(repository.getOwner(), repository.getName(), repoProps);
.getApiInterface(ctx)
.repoEdit(repository.getOwner(), repository.getName(), repoProps);
propsCall.enqueue(new Callback<Repository>() { propsCall.enqueue(new Callback<Repository>() {
@ -327,8 +316,7 @@ public class RepositorySettingsActivity extends BaseActivity {
repository.setRepository(response.body()); repository.setRepository(response.body());
if(!repository.getName().equals(repoName)) { if(!repository.getName().equals(repoName)) {
Objects.requireNonNull(BaseApi.getInstance(ctx, RepositoriesApi.class)) Objects.requireNonNull(BaseApi.getInstance(ctx, RepositoriesApi.class)).updateRepositoryOwnerAndName(repository.getOwner(), repoName, repository.getRepositoryId());
.updateRepositoryOwnerAndName(repository.getOwner(), repoName, repository.getRepositoryId());
Intent result = new Intent(); Intent result = new Intent();
result.putExtra("nameChanged", true); result.putExtra("nameChanged", true);
setResult(200, result); setResult(200, result);

View File

@ -25,16 +25,13 @@ import org.mian.gitnex.helpers.Toasty;
public class SettingsAppearanceActivity extends BaseActivity { public class SettingsAppearanceActivity extends BaseActivity {
private View.OnClickListener onClickListener;
private static String[] timeList; private static String[] timeList;
private static int timeSelectedChoice = 0; private static int timeSelectedChoice = 0;
private static String[] customFontList; private static String[] customFontList;
private static int customFontSelectedChoice = 0; private static int customFontSelectedChoice = 0;
private static String[] themeList; private static String[] themeList;
private static int themeSelectedChoice = 0; private static int themeSelectedChoice = 0;
private View.OnClickListener onClickListener;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -63,22 +60,28 @@ public class SettingsAppearanceActivity extends BaseActivity {
String lightMinute = String.valueOf(tinyDB.getInt("lightThemeTimeMinute")); String lightMinute = String.valueOf(tinyDB.getInt("lightThemeTimeMinute"));
String lightHour = String.valueOf(tinyDB.getInt("lightThemeTimeHour")); String lightHour = String.valueOf(tinyDB.getInt("lightThemeTimeHour"));
if(lightMinute.length() == 1) lightMinute = "0" + lightMinute; if(lightMinute.length() == 1) {
if(lightHour.length() == 1) lightHour = "0" + lightHour; lightMinute = "0" + lightMinute;
}
if(lightHour.length() == 1) {
lightHour = "0" + lightHour;
}
String darkMinute = String.valueOf(tinyDB.getInt("darkThemeTimeMinute")); String darkMinute = String.valueOf(tinyDB.getInt("darkThemeTimeMinute"));
String darkHour = String.valueOf(tinyDB.getInt("darkThemeTimeHour")); String darkHour = String.valueOf(tinyDB.getInt("darkThemeTimeHour"));
if(darkMinute.length() == 1) darkMinute = "0" + darkMinute; if(darkMinute.length() == 1) {
if(darkHour.length() == 1) darkHour = "0" + darkHour; darkMinute = "0" + darkMinute;
}
if(darkHour.length() == 1) {
darkHour = "0" + darkHour;
}
timeSelectedChoice = tinyDB.getInt("timeId"); timeSelectedChoice = tinyDB.getInt("timeId");
customFontSelectedChoice = tinyDB.getInt("customFontId", 1); customFontSelectedChoice = tinyDB.getInt("customFontId", 1);
themeSelectedChoice = tinyDB.getInt("themeId", 6); // use system theme as default themeSelectedChoice = tinyDB.getInt("themeId", 6); // use system theme as default
activitySettingsAppearanceBinding.lightThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, lightHour, activitySettingsAppearanceBinding.lightThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, lightHour, lightMinute));
lightMinute)); activitySettingsAppearanceBinding.darkThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, darkHour, darkMinute));
activitySettingsAppearanceBinding.darkThemeSelectedTime.setText(ctx.getResources().getString(R.string.settingsThemeTimeSelectedHint, darkHour,
darkMinute));
activitySettingsAppearanceBinding.tvDateTimeSelected.setText(timeList[timeSelectedChoice]); activitySettingsAppearanceBinding.tvDateTimeSelected.setText(timeList[timeSelectedChoice]);
activitySettingsAppearanceBinding.customFontSelected.setText(customFontList[customFontSelectedChoice]); activitySettingsAppearanceBinding.customFontSelected.setText(customFontList[customFontSelectedChoice]);
activitySettingsAppearanceBinding.themeSelected.setText(themeList[themeSelectedChoice]); activitySettingsAppearanceBinding.themeSelected.setText(themeList[themeSelectedChoice]);
@ -110,13 +113,13 @@ public class SettingsAppearanceActivity extends BaseActivity {
tinyDB.putBoolean("showLabelsInList", isChecked); tinyDB.putBoolean("showLabelsInList", isChecked);
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
activitySettingsAppearanceBinding.labelsInListFrame.setOnClickListener(v -> activitySettingsAppearanceBinding.switchLabelsInListBadge.setChecked(!activitySettingsAppearanceBinding.switchLabelsInListBadge.isChecked())); activitySettingsAppearanceBinding.labelsInListFrame.setOnClickListener(
v -> activitySettingsAppearanceBinding.switchLabelsInListBadge.setChecked(!activitySettingsAppearanceBinding.switchLabelsInListBadge.isChecked()));
// theme selection dialog // theme selection dialog
themeFrame.setOnClickListener(view -> { themeFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.themeSelectorDialogTitle)
.setTitle(R.string.themeSelectorDialogTitle)
.setSingleChoiceItems(themeList, themeSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(themeList, themeSelectedChoice, (dialogInterfaceTheme, i) -> {
themeSelectedChoice = i; themeSelectedChoice = i;
@ -146,9 +149,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
// custom font dialog // custom font dialog
customFontFrame.setOnClickListener(view -> { customFontFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsCustomFontSelectorDialogTitle).setCancelable(customFontSelectedChoice != -1)
.setTitle(R.string.settingsCustomFontSelectorDialogTitle)
.setCancelable(customFontSelectedChoice != -1)
.setSingleChoiceItems(customFontList, customFontSelectedChoice, (dialogInterfaceCustomFont, i) -> { .setSingleChoiceItems(customFontList, customFontSelectedChoice, (dialogInterfaceCustomFont, i) -> {
customFontSelectedChoice = i; customFontSelectedChoice = i;
@ -170,9 +171,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
// time and date dialog // time and date dialog
timeFrame.setOnClickListener(view -> { timeFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsTimeSelectorDialogTitle).setCancelable(timeSelectedChoice != -1)
.setTitle(R.string.settingsTimeSelectorDialogTitle)
.setCancelable(timeSelectedChoice != -1)
.setSingleChoiceItems(timeList, timeSelectedChoice, (dialogInterfaceTime, i) -> { .setSingleChoiceItems(timeList, timeSelectedChoice, (dialogInterfaceTime, i) -> {
timeSelectedChoice = i; timeSelectedChoice = i;
@ -224,6 +223,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave)); Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave));
requireActivity().recreate(); requireActivity().recreate();
} }
} }
public static class DarkTimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener { public static class DarkTimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@ -249,6 +249,7 @@ public class SettingsAppearanceActivity extends BaseActivity {
Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave)); Toasty.success(requireActivity().getApplicationContext(), requireContext().getResources().getString(R.string.settingsSave));
requireActivity().recreate(); requireActivity().recreate();
} }
} }
} }

View File

@ -41,6 +41,8 @@ public class SettingsDraftsActivity extends BaseActivity {
} }
private void initCloseListener() { onClickListener = view -> finish(); } private void initCloseListener() {
onClickListener = view -> finish();
}
} }

View File

@ -16,14 +16,12 @@ import java.util.List;
public class SettingsGeneralActivity extends BaseActivity { public class SettingsGeneralActivity extends BaseActivity {
private static int homeScreenSelectedChoice = 0;
private static int defaultLinkHandlerScreenSelectedChoice = 0;
private ActivitySettingsGeneralBinding viewBinding; private ActivitySettingsGeneralBinding viewBinding;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private List<String> homeScreenList; private List<String> homeScreenList;
private static int homeScreenSelectedChoice = 0;
private List<String> linkHandlerDefaultScreen; private List<String> linkHandlerDefaultScreen;
private static int defaultLinkHandlerScreenSelectedChoice = 0;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -100,9 +98,7 @@ public class SettingsGeneralActivity extends BaseActivity {
viewBinding.homeScreenFrame.setOnClickListener(setDefaultHomeScreen -> { viewBinding.homeScreenFrame.setOnClickListener(setDefaultHomeScreen -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsHomeScreenSelectorDialogTitle).setCancelable(homeScreenSelectedChoice != -1)
.setTitle(R.string.settingsHomeScreenSelectorDialogTitle)
.setCancelable(homeScreenSelectedChoice != -1)
.setSingleChoiceItems(homeScreenArray, homeScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> { .setSingleChoiceItems(homeScreenArray, homeScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> {
homeScreenSelectedChoice = i; homeScreenSelectedChoice = i;
@ -129,9 +125,7 @@ public class SettingsGeneralActivity extends BaseActivity {
viewBinding.setDefaultLinkHandler.setOnClickListener(setDefaultLinkHandler -> { viewBinding.setDefaultLinkHandler.setOnClickListener(setDefaultLinkHandler -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.linkSelectorDialogTitle).setCancelable(defaultLinkHandlerScreenSelectedChoice != -1)
.setTitle(R.string.linkSelectorDialogTitle)
.setCancelable(defaultLinkHandlerScreenSelectedChoice != -1)
.setSingleChoiceItems(linksArray, defaultLinkHandlerScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> { .setSingleChoiceItems(linksArray, defaultLinkHandlerScreenSelectedChoice, (dialogInterfaceHomeScreen, i) -> {
defaultLinkHandlerScreenSelectedChoice = i; defaultLinkHandlerScreenSelectedChoice = i;
@ -156,5 +150,8 @@ public class SettingsGeneralActivity extends BaseActivity {
// custom tabs // custom tabs
} }
private void initCloseListener() { onClickListener = view -> finish(); } private void initCloseListener() {
onClickListener = view -> finish();
}
} }

View File

@ -42,12 +42,7 @@ public class SettingsNotificationsActivity extends BaseActivity {
viewBinding.enableVibrationMode.setChecked(tinyDB.getBoolean("notificationsEnableVibration", true)); viewBinding.enableVibrationMode.setChecked(tinyDB.getBoolean("notificationsEnableVibration", true));
if(!viewBinding.enableNotificationsMode.isChecked()) { if(!viewBinding.enableNotificationsMode.isChecked()) {
AppUtil.setMultiVisibility(View.GONE, AppUtil.setMultiVisibility(View.GONE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame,
viewBinding.enableLightsFrame,
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} }
if(!viewBinding.enableLightsMode.isChecked()) { if(!viewBinding.enableLightsMode.isChecked()) {
@ -60,27 +55,17 @@ public class SettingsNotificationsActivity extends BaseActivity {
if(isChecked) { if(isChecked) {
Notifications.startWorker(ctx); Notifications.startWorker(ctx);
AppUtil.setMultiVisibility(View.VISIBLE, AppUtil.setMultiVisibility(View.VISIBLE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame, }
viewBinding.enableLightsFrame, else {
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} else {
Notifications.stopWorker(ctx); Notifications.stopWorker(ctx);
AppUtil.setMultiVisibility(View.GONE, AppUtil.setMultiVisibility(View.GONE, viewBinding.chooseColorFrame, viewBinding.enableLightsFrame, viewBinding.enableVibrationFrame, viewBinding.pollingDelayFrame);
viewBinding.chooseColorFrame,
viewBinding.enableLightsFrame,
viewBinding.enableVibrationFrame,
viewBinding.pollingDelayFrame
);
} }
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
viewBinding.enableNotificationsFrame.setOnClickListener( viewBinding.enableNotificationsFrame.setOnClickListener(v -> viewBinding.enableNotificationsMode.setChecked(!viewBinding.enableNotificationsMode.isChecked()));
v -> viewBinding.enableNotificationsMode.setChecked(!viewBinding.enableNotificationsMode.isChecked()));
// polling delay // polling delay
viewBinding.pollingDelayFrame.setOnClickListener(v -> { viewBinding.pollingDelayFrame.setOnClickListener(v -> {
@ -91,12 +76,8 @@ public class SettingsNotificationsActivity extends BaseActivity {
numberPicker.setValue(tinyDB.getInt("pollingDelayMinutes", Constants.defaultPollingDelay)); numberPicker.setValue(tinyDB.getInt("pollingDelayMinutes", Constants.defaultPollingDelay));
numberPicker.setWrapSelectorWheel(true); numberPicker.setWrapSelectorWheel(true);
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.pollingDelayDialogHeaderText).setMessage(getString(R.string.pollingDelayDialogDescriptionText))
.setTitle(R.string.pollingDelayDialogHeaderText) .setCancelable(true).setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(getString(R.string.okButton), (dialog, which) -> {
.setMessage(getString(R.string.pollingDelayDialogDescriptionText))
.setCancelable(true)
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(getString(R.string.okButton), (dialog, which) -> {
tinyDB.putInt("pollingDelayMinutes", numberPicker.getValue()); tinyDB.putInt("pollingDelayMinutes", numberPicker.getValue());
@ -116,7 +97,8 @@ public class SettingsNotificationsActivity extends BaseActivity {
if(!isChecked) { if(!isChecked) {
viewBinding.chooseColorFrame.setVisibility(View.GONE); viewBinding.chooseColorFrame.setVisibility(View.GONE);
} else { }
else {
viewBinding.chooseColorFrame.setVisibility(View.VISIBLE); viewBinding.chooseColorFrame.setVisibility(View.VISIBLE);
} }
@ -150,8 +132,7 @@ public class SettingsNotificationsActivity extends BaseActivity {
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
viewBinding.enableVibrationFrame.setOnClickListener( viewBinding.enableVibrationFrame.setOnClickListener(v -> viewBinding.enableVibrationMode.setChecked(!viewBinding.enableVibrationMode.isChecked()));
v -> viewBinding.enableVibrationMode.setChecked(!viewBinding.enableVibrationMode.isChecked()));
} }

View File

@ -36,8 +36,7 @@ public class SettingsReportsActivity extends BaseActivity {
tinyDB.putBoolean("crashReportingEnabled", isChecked); tinyDB.putBoolean("crashReportingEnabled", isChecked);
Toasty.success(appCtx, getResources().getString(R.string.settingsSave)); Toasty.success(appCtx, getResources().getString(R.string.settingsSave));
}); });
activitySettingsReportsBinding.enableSendReports.setOnClickListener( activitySettingsReportsBinding.enableSendReports.setOnClickListener(v -> activitySettingsReportsBinding.crashReportsSwitch.setChecked(!activitySettingsReportsBinding.crashReportsSwitch.isChecked()));
v -> activitySettingsReportsBinding.crashReportsSwitch.setChecked(!activitySettingsReportsBinding.crashReportsSwitch.isChecked()));
} }
private void initCloseListener() { private void initCloseListener() {

View File

@ -28,13 +28,11 @@ import static androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTI
public class SettingsSecurityActivity extends BaseActivity { public class SettingsSecurityActivity extends BaseActivity {
private View.OnClickListener onClickListener;
private static String[] cacheSizeDataList; private static String[] cacheSizeDataList;
private static int cacheSizeDataSelectedChoice = 0; private static int cacheSizeDataSelectedChoice = 0;
private static String[] cacheSizeImagesList; private static String[] cacheSizeImagesList;
private static int cacheSizeImagesSelectedChoice = 0; private static int cacheSizeImagesSelectedChoice = 0;
private View.OnClickListener onClickListener;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -141,11 +139,8 @@ public class SettingsSecurityActivity extends BaseActivity {
// clear cache // clear cache
clearCacheFrame.setOnClickListener(v1 -> { clearCacheFrame.setOnClickListener(v1 -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.clearCacheDialogHeader).setMessage(getResources().getString(R.string.clearCacheDialogMessage))
.setTitle(R.string.clearCacheDialogHeader) .setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
.setMessage(getResources().getString(R.string.clearCacheDialogMessage))
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
try { try {
@ -166,9 +161,7 @@ public class SettingsSecurityActivity extends BaseActivity {
// cache size images selection dialog // cache size images selection dialog
cacheSizeImagesFrame.setOnClickListener(view -> { cacheSizeImagesFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.cacheSizeImagesDialogHeader).setCancelable(cacheSizeImagesSelectedChoice != -1)
.setTitle(R.string.cacheSizeImagesDialogHeader)
.setCancelable(cacheSizeImagesSelectedChoice != -1)
.setSingleChoiceItems(cacheSizeImagesList, cacheSizeImagesSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(cacheSizeImagesList, cacheSizeImagesSelectedChoice, (dialogInterfaceTheme, i) -> {
cacheSizeImagesSelectedChoice = i; cacheSizeImagesSelectedChoice = i;
@ -186,9 +179,7 @@ public class SettingsSecurityActivity extends BaseActivity {
// cache size data selection dialog // cache size data selection dialog
cacheSizeDataFrame.setOnClickListener(view -> { cacheSizeDataFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.cacheSizeDataDialogHeader).setCancelable(cacheSizeDataSelectedChoice != -1)
.setTitle(R.string.cacheSizeDataDialogHeader)
.setCancelable(cacheSizeDataSelectedChoice != -1)
.setSingleChoiceItems(cacheSizeDataList, cacheSizeDataSelectedChoice, (dialogInterfaceTheme, i) -> { .setSingleChoiceItems(cacheSizeDataList, cacheSizeDataSelectedChoice, (dialogInterfaceTheme, i) -> {
cacheSizeDataSelectedChoice = i; cacheSizeDataSelectedChoice = i;
@ -206,11 +197,8 @@ public class SettingsSecurityActivity extends BaseActivity {
// certs deletion // certs deletion
certsFrame.setOnClickListener(v1 -> { certsFrame.setOnClickListener(v1 -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsCertsPopupTitle).setMessage(getResources().getString(R.string.settingsCertsPopupMessage))
.setTitle(R.string.settingsCertsPopupTitle) .setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
.setMessage(getResources().getString(R.string.settingsCertsPopupMessage))
.setNeutralButton(R.string.cancelButton, (dialog, which) -> dialog.dismiss())
.setPositiveButton(R.string.menuDeleteText, (dialog, which) -> {
appCtx.getSharedPreferences(MemorizingTrustManager.KEYSTORE_NAME, Context.MODE_PRIVATE).edit().remove(MemorizingTrustManager.KEYSTORE_KEY).apply(); appCtx.getSharedPreferences(MemorizingTrustManager.KEYSTORE_NAME, Context.MODE_PRIVATE).edit().remove(MemorizingTrustManager.KEYSTORE_KEY).apply();
AppUtil.logout(this); AppUtil.logout(this);
@ -224,4 +212,5 @@ public class SettingsSecurityActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
} }

View File

@ -20,9 +20,14 @@ import java.util.Locale;
public class SettingsTranslationActivity extends BaseActivity { public class SettingsTranslationActivity extends BaseActivity {
private static int langSelectedChoice = 0;
private View.OnClickListener onClickListener; private View.OnClickListener onClickListener;
private static int langSelectedChoice = 0; private static String getLanguageDisplayName(String langCode) {
Locale english = new Locale("en");
Locale translated = new Locale(langCode);
return String.format("%s (%s)", translated.getDisplayName(translated), translated.getDisplayName(english));
}
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@ -58,11 +63,8 @@ public class SettingsTranslationActivity extends BaseActivity {
// language dialog // language dialog
langFrame.setOnClickListener(view -> { langFrame.setOnClickListener(view -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(R.string.settingsLanguageSelectorDialogTitle).setCancelable(langSelectedChoice != -1)
.setTitle(R.string.settingsLanguageSelectorDialogTitle) .setNeutralButton(getString(R.string.cancelButton), null).setSingleChoiceItems(langs.values().toArray(new String[0]), langSelectedChoice, (dialogInterface, i) -> {
.setCancelable(langSelectedChoice != -1)
.setNeutralButton(getString(R.string.cancelButton), null)
.setSingleChoiceItems(langs.values().toArray(new String[0]), langSelectedChoice, (dialogInterface, i) -> {
String selectedLanguage = langs.keySet().toArray(new String[0])[i]; String selectedLanguage = langs.keySet().toArray(new String[0])[i];
tinyDB.putInt("langId", i); tinyDB.putInt("langId", i);
@ -84,10 +86,4 @@ public class SettingsTranslationActivity extends BaseActivity {
onClickListener = view -> finish(); onClickListener = view -> finish();
} }
private static String getLanguageDisplayName(String langCode) {
Locale english = new Locale("en");
Locale translated = new Locale(langCode);
return String.format("%s (%s)", translated.getDisplayName(translated), translated.getDisplayName(english));
}
} }

View File

@ -105,9 +105,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
createWikiPageOptions.setTitle(wikiTitle); createWikiPageOptions.setTitle(wikiTitle);
createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent)); createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent));
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoCreateWikiPage(repository.getOwner(), repository.getName(), createWikiPageOptions);
.getApiInterface(ctx)
.repoCreateWikiPage(repository.getOwner(), repository.getName(), createWikiPageOptions);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -155,9 +153,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
createWikiPageOptions.setTitle(wikiTitle); createWikiPageOptions.setTitle(wikiTitle);
createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent)); createWikiPageOptions.setContentBase64(AppUtil.encodeBase64(wikiContent));
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoEditWikiPage(repository.getOwner(), repository.getName(), pageName, createWikiPageOptions);
.getApiInterface(ctx)
.repoEditWikiPage(repository.getOwner(), repository.getName(), pageName, createWikiPageOptions);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,9 +197,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
private void getWikiPageContents() { private void getWikiPageContents() {
Call<WikiPage> call = RetrofitClient Call<WikiPage> call = RetrofitClient.getApiInterface(ctx).repoGetWikiPage(repository.getOwner(), repository.getName(), pageName);
.getApiInterface(ctx)
.repoGetWikiPage(repository.getOwner(), repository.getName(), pageName);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -269,12 +263,9 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
private void deleteWiki(final String owner, final String repo, final String pageName) { private void deleteWiki(final String owner, final String repo, final String pageName) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(String.format(ctx.getString(R.string.deleteGenericTitle), pageName))
.setTitle(String.format(ctx.getString(R.string.deleteGenericTitle), pageName)) .setMessage(ctx.getString(R.string.deleteWikiPageMessage, pageName)).setNeutralButton(R.string.cancelButton, null)
.setMessage(ctx.getString(R.string.deleteWikiPageMessage, pageName)) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(ctx).repoDeleteWikiPage(owner, repo, pageName).enqueue(new Callback<>() {
.setNeutralButton(R.string.cancelButton, null)
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(ctx).repoDeleteWikiPage(owner, repo, pageName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
@ -362,8 +353,7 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
if(action.equalsIgnoreCase("edit") || action.equalsIgnoreCase("add")) { if(action.equalsIgnoreCase("edit") || action.equalsIgnoreCase("add")) {
if(renderMd) { if(renderMd) {
Markdown.render(ctx, EmojiParser.parseToUnicode(String.valueOf( Markdown.render(ctx, EmojiParser.parseToUnicode(String.valueOf(Objects.requireNonNull(binding.contentLayout.getEditText()).getText())), binding.markdownPreview, repository);
Objects.requireNonNull(binding.contentLayout.getEditText()).getText())), binding.markdownPreview, repository);
binding.markdownPreview.setVisibility(View.VISIBLE); binding.markdownPreview.setVisibility(View.VISIBLE);
binding.contentLayout.setVisibility(View.GONE); binding.contentLayout.setVisibility(View.GONE);
@ -402,4 +392,5 @@ public class WikiActivity extends BaseActivity implements BottomSheetListener {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
} }

View File

@ -31,90 +31,13 @@ public class AdminCronTasksAdapter extends RecyclerView.Adapter<AdminCronTasksAd
private final List<Cron> tasksList; private final List<Cron> tasksList;
static class CronTasksViewHolder extends RecyclerView.ViewHolder {
private Cron cronTasks;
private final TextView taskName;
private CronTasksViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
final Locale locale = ctx.getResources().getConfiguration().locale;
final String timeFormat = TinyDB.getInstance(ctx).getString("dateFormat", "pretty");
ImageView runTask = itemView.findViewById(R.id.runTask);
taskName = itemView.findViewById(R.id.taskName);
LinearLayout cronTasksInfo = itemView.findViewById(R.id.cronTasksInfo);
LinearLayout cronTasksRun = itemView.findViewById(R.id.cronTasksRun);
cronTasksInfo.setOnClickListener(taskInfo -> {
String nextRun = "";
String lastRun = "";
if(cronTasks.getNext() != null) {
nextRun = TimeHelper.formatTime(cronTasks.getNext(), locale, timeFormat, ctx);
}
if(cronTasks.getPrev() != null) {
lastRun = TimeHelper.formatTime(cronTasks.getPrev(), locale, timeFormat, ctx);
}
View view = LayoutInflater.from(ctx).inflate(R.layout.layout_cron_task_info, null);
TextView taskScheduleContent = view.findViewById(R.id.taskScheduleContent);
TextView nextRunContent = view.findViewById(R.id.nextRunContent);
TextView lastRunContent = view.findViewById(R.id.lastRunContent);
TextView execTimeContent = view.findViewById(R.id.execTimeContent);
taskScheduleContent.setText(cronTasks.getSchedule());
nextRunContent.setText(nextRun);
lastRunContent.setText(lastRun);
execTimeContent.setText(String.valueOf(cronTasks.getExecTimes()));
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx)
.setTitle(StringUtils.capitalize(cronTasks.getName().replace("_", " ")))
.setView(view)
.setPositiveButton(ctx.getString(R.string.close), null);
materialAlertDialogBuilder.create().show();
});
cronTasksRun.setOnClickListener(taskInfo -> {
runCronTask(ctx, cronTasks.getName());
});
}
}
public AdminCronTasksAdapter(List<Cron> tasksListMain) { public AdminCronTasksAdapter(List<Cron> tasksListMain) {
this.tasksList = tasksListMain; this.tasksList = tasksListMain;
} }
@NonNull
@Override
public AdminCronTasksAdapter.CronTasksViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_admin_cron_tasks, parent, false);
return new AdminCronTasksAdapter.CronTasksViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AdminCronTasksAdapter.CronTasksViewHolder holder, int position) {
Cron currentItem = tasksList.get(position);
holder.cronTasks = currentItem;
holder.taskName.setText(StringUtils.capitalize(currentItem.getName().replace("_", " ")));
}
private static void runCronTask(final Context ctx, final String taskName) { private static void runCronTask(final Context ctx, final String taskName) {
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminCronRun(taskName);
.getApiInterface(ctx)
.adminCronRun(taskName);
call.enqueue(new Callback<Void>() { call.enqueue(new Callback<Void>() {
@ -153,8 +76,82 @@ public class AdminCronTasksAdapter extends RecyclerView.Adapter<AdminCronTasksAd
}); });
} }
@NonNull
@Override
public AdminCronTasksAdapter.CronTasksViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_admin_cron_tasks, parent, false);
return new AdminCronTasksAdapter.CronTasksViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull AdminCronTasksAdapter.CronTasksViewHolder holder, int position) {
Cron currentItem = tasksList.get(position);
holder.cronTasks = currentItem;
holder.taskName.setText(StringUtils.capitalize(currentItem.getName().replace("_", " ")));
}
@Override @Override
public int getItemCount() { public int getItemCount() {
return tasksList.size(); return tasksList.size();
} }
static class CronTasksViewHolder extends RecyclerView.ViewHolder {
private final TextView taskName;
private Cron cronTasks;
private CronTasksViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
final Locale locale = ctx.getResources().getConfiguration().locale;
final String timeFormat = TinyDB.getInstance(ctx).getString("dateFormat", "pretty");
ImageView runTask = itemView.findViewById(R.id.runTask);
taskName = itemView.findViewById(R.id.taskName);
LinearLayout cronTasksInfo = itemView.findViewById(R.id.cronTasksInfo);
LinearLayout cronTasksRun = itemView.findViewById(R.id.cronTasksRun);
cronTasksInfo.setOnClickListener(taskInfo -> {
String nextRun = "";
String lastRun = "";
if(cronTasks.getNext() != null) {
nextRun = TimeHelper.formatTime(cronTasks.getNext(), locale, timeFormat, ctx);
}
if(cronTasks.getPrev() != null) {
lastRun = TimeHelper.formatTime(cronTasks.getPrev(), locale, timeFormat, ctx);
}
View view = LayoutInflater.from(ctx).inflate(R.layout.layout_cron_task_info, null);
TextView taskScheduleContent = view.findViewById(R.id.taskScheduleContent);
TextView nextRunContent = view.findViewById(R.id.nextRunContent);
TextView lastRunContent = view.findViewById(R.id.lastRunContent);
TextView execTimeContent = view.findViewById(R.id.execTimeContent);
taskScheduleContent.setText(cronTasks.getSchedule());
nextRunContent.setText(nextRun);
lastRunContent.setText(lastRun);
execTimeContent.setText(String.valueOf(cronTasks.getExecTimes()));
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(StringUtils.capitalize(cronTasks.getName().replace("_", " "))).setView(view)
.setPositiveButton(ctx.getString(R.string.close), null);
materialAlertDialogBuilder.create().show();
});
cronTasksRun.setOnClickListener(taskInfo -> {
runCronTask(ctx, cronTasks.getName());
});
}
}
} }

View File

@ -30,11 +30,43 @@ import java.util.List;
public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private List<User> usersList;
private final List<User> usersListFull; private final List<User> usersListFull;
private final Context context; private final Context context;
private List<User> usersList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final Filter usersFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(usersListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(User item : usersListFull) {
if(item.getEmail().toLowerCase().contains(filterPattern) || item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
usersList.clear();
usersList.addAll((List) results.values);
notifyDataChanged();
}
};
public AdminGetUsersAdapter(List<User> usersListMain, Context ctx) { public AdminGetUsersAdapter(List<User> usersListMain, Context ctx) {
this.context = ctx; this.context = ctx;
@ -69,14 +101,50 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
return usersList.size(); return usersList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
usersList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return usersFilter;
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class ReposHolder extends RecyclerView.ViewHolder { class ReposHolder extends RecyclerView.ViewHolder {
private String userLoginId;
private final ImageView userAvatar; private final ImageView userAvatar;
private final TextView userFullName; private final TextView userFullName;
private final TextView userEmail; private final TextView userEmail;
private final ImageView userRole; private final ImageView userRole;
private final TextView userName; private final TextView userName;
private String userLoginId;
ReposHolder(View itemView) { ReposHolder(View itemView) {
@ -126,9 +194,8 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
if(users.isIsAdmin()) { if(users.isIsAdmin()) {
userRole.setVisibility(View.VISIBLE); userRole.setVisibility(View.VISIBLE);
TextDrawable drawable = TextDrawable.builder().beginConfig() TextDrawable drawable = TextDrawable.builder().beginConfig().textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(60).width(200).height(80).endConfig()
.textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(60).width(200).height(80) .buildRoundRect(context.getResources().getString(R.string.userRoleAdmin).toLowerCase(), ResourcesCompat.getColor(context.getResources(), R.color.releasePre, null), 8);
.endConfig().buildRoundRect(context.getResources().getString(R.string.userRoleAdmin).toLowerCase(), ResourcesCompat.getColor(context.getResources(), R.color.releasePre, null), 8);
userRole.setImageDrawable(drawable); userRole.setImageDrawable(drawable);
} }
else { else {
@ -138,71 +205,7 @@ public class AdminGetUsersAdapter extends RecyclerView.Adapter<RecyclerView.View
PicassoService.getInstance(context).get().load(users.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(userAvatar); PicassoService.getInstance(context).get().load(users.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(userAvatar);
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
usersList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return usersFilter;
}
private final Filter usersFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(usersListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (User item : usersListFull) {
if (item.getEmail().toLowerCase().contains(filterPattern) || item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
usersList.clear();
usersList.addAll((List) results.values);
notifyDataChanged();
}
};
} }

View File

@ -25,37 +25,11 @@ import retrofit2.Callback;
public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadoptedReposAdapter.UnadoptedViewHolder> { public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadoptedReposAdapter.UnadoptedViewHolder> {
private List<String> repos;
private final Runnable updateList; private final Runnable updateList;
private final Runnable loadMoreListener; private final Runnable loadMoreListener;
private boolean isLoading = false, hasMore = true;
private final ActivityAdminCronTasksBinding activityAdminCronTasksBinding; private final ActivityAdminCronTasksBinding activityAdminCronTasksBinding;
private List<String> repos;
class UnadoptedViewHolder extends RecyclerView.ViewHolder { private boolean isLoading = false, hasMore = true;
private String repoName;
private final TextView name;
private UnadoptedViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
name = itemView.findViewById(R.id.repo_name);
itemView.setOnClickListener(taskInfo -> {
String[] repoSplit = repoName.split("/");
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx)
.setTitle(repoName).setMessage(ctx.getString(R.string.unadoptedReposMessage, repoSplit[1], repoSplit[0]))
.setNeutralButton(R.string.close, null)
.setPositiveButton(R.string.menuDeleteText, ((dialog, which) -> delete(ctx, repoName)))
.setNegativeButton(R.string.adoptRepo, ((dialog, which) -> adopt(ctx, repoName, getBindingAdapterPosition())));
materialAlertDialogBuilder.create().show();
});
}
}
public AdminUnadoptedReposAdapter(List<String> list, Runnable updateList, Runnable loadMore, ActivityAdminCronTasksBinding activityAdminCronTasksBinding) { public AdminUnadoptedReposAdapter(List<String> list, Runnable updateList, Runnable loadMore, ActivityAdminCronTasksBinding activityAdminCronTasksBinding) {
this.repos = list; this.repos = list;
@ -95,9 +69,7 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
String[] repoSplit = name.split("/"); String[] repoSplit = name.split("/");
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminDeleteUnadoptedRepository(repoSplit[0], repoSplit[1]);
.getApiInterface(ctx)
.adminDeleteUnadoptedRepository(repoSplit[0], repoSplit[1]);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -141,9 +113,7 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
String[] repoSplit = name.split("/"); String[] repoSplit = name.split("/");
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(ctx).adminAdoptRepository(repoSplit[0], repoSplit[1]);
.getApiInterface(ctx)
.adminAdoptRepository(repoSplit[0], repoSplit[1]);
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -201,4 +171,30 @@ public class AdminUnadoptedReposAdapter extends RecyclerView.Adapter<AdminUnadop
this.hasMore = hasMore; this.hasMore = hasMore;
isLoading = false; isLoading = false;
} }
class UnadoptedViewHolder extends RecyclerView.ViewHolder {
private final TextView name;
private String repoName;
private UnadoptedViewHolder(View itemView) {
super(itemView);
Context ctx = itemView.getContext();
name = itemView.findViewById(R.id.repo_name);
itemView.setOnClickListener(taskInfo -> {
String[] repoSplit = repoName.split("/");
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ctx).setTitle(repoName).setMessage(ctx.getString(R.string.unadoptedReposMessage, repoSplit[1], repoSplit[0]))
.setNeutralButton(R.string.close, null).setPositiveButton(R.string.menuDeleteText, ((dialog, which) -> delete(ctx, repoName)))
.setNegativeButton(R.string.adoptRepo, ((dialog, which) -> adopt(ctx, repoName, getBindingAdapterPosition())));
materialAlertDialogBuilder.create().show();
});
}
}
} }

View File

@ -28,16 +28,10 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
private final Context context; private final Context context;
private final List<User> assigneesList; private final List<User> assigneesList;
private final AssigneesListAdapterListener assigneesListener;
private List<String> assigneesStrings = new ArrayList<>(); private List<String> assigneesStrings = new ArrayList<>();
private List<String> currentAssignees; private List<String> currentAssignees;
private final AssigneesListAdapterListener assigneesListener;
public interface AssigneesListAdapterListener {
void assigneesInterface(List<String> data);
}
public AssigneesListAdapter(Context ctx, List<User> dataMain, AssigneesListAdapterListener assigneesListener, List<String> currentAssignees) { public AssigneesListAdapter(Context ctx, List<User> dataMain, AssigneesListAdapterListener assigneesListener, List<String> currentAssignees) {
this.context = ctx; this.context = ctx;
@ -46,23 +40,6 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
this.currentAssignees = currentAssignees; this.currentAssignees = currentAssignees;
} }
static class AssigneesViewHolder extends RecyclerView.ViewHolder {
private final CheckBox assigneesSelection;
private final TextView assigneesName;
private final ImageView assigneesAvatar;
private AssigneesViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
assigneesSelection = itemView.findViewById(R.id.assigneesSelection);
assigneesName = itemView.findViewById(R.id.assigneesName);
assigneesAvatar = itemView.findViewById(R.id.assigneesAvatar);
}
}
@NonNull @NonNull
@Override @Override
public AssigneesListAdapter.AssigneesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public AssigneesListAdapter.AssigneesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -85,8 +62,8 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
holder.assigneesName.setText(Html.fromHtml(currentItem.getFullName())); holder.assigneesName.setText(Html.fromHtml(currentItem.getFullName()));
} }
PicassoService PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop()
.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop().into(holder.assigneesAvatar); .into(holder.assigneesAvatar);
for(int i = 0; i < assigneesList.size(); i++) { for(int i = 0; i < assigneesList.size(); i++) {
@ -138,4 +115,29 @@ public class AssigneesListAdapter extends RecyclerView.Adapter<AssigneesListAdap
currentAssignees = list; currentAssignees = list;
notifyDataSetChanged(); notifyDataSetChanged();
} }
public interface AssigneesListAdapterListener {
void assigneesInterface(List<String> data);
}
static class AssigneesViewHolder extends RecyclerView.ViewHolder {
private final CheckBox assigneesSelection;
private final TextView assigneesName;
private final ImageView assigneesAvatar;
private AssigneesViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
assigneesSelection = itemView.findViewById(R.id.assigneesSelection);
assigneesName = itemView.findViewById(R.id.assigneesName);
assigneesAvatar = itemView.findViewById(R.id.assigneesAvatar);
}
}
} }

View File

@ -47,66 +47,6 @@ public class CollaboratorSearchAdapter extends RecyclerView.Adapter<Collaborator
this.repository = repository; this.repository = repository;
} }
class CollaboratorSearchViewHolder extends RecyclerView.ViewHolder {
private User userInfo;
private final ImageView userAvatar;
private final TextView userFullName;
private final TextView userName;
private final ImageView addCollaboratorButtonAdd;
private final ImageView addCollaboratorButtonRemove;
private final String[] permissionList = {"Read", "Write", "Admin"};
final private int permissionSelectedChoice = 0;
private CollaboratorSearchViewHolder(View itemView) {
super(itemView);
userAvatar = itemView.findViewById(R.id.userAvatar);
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addCollaboratorButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addCollaboratorButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
addCollaboratorButtonAdd.setOnClickListener(v -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context)
.setTitle(R.string.newTeamPermission)
.setSingleChoiceItems(permissionList, permissionSelectedChoice, null)
.setNeutralButton(R.string.cancelButton, null)
.setPositiveButton(R.string.addButton, (dialog, which) -> {
ListView lw = ((AlertDialog)dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());
CollaboratorActions.addCollaborator(context, String.valueOf(checkedItem).toLowerCase(), userInfo.getLogin(), repository);
});
materialAlertDialogBuilder.create().show();
});
addCollaboratorButtonRemove.setOnClickListener(v -> AlertDialogs.collaboratorRemoveDialog(context, userInfo.getLogin(), repository));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(userInfo.getLogin())) {
userAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userInfo.getLogin());
context.startActivity(intent);
});
userAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin()));
return true;
});
}
}, 500);
}
}
@NonNull @NonNull
@Override @Override
public CollaboratorSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public CollaboratorSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -133,16 +73,15 @@ public class CollaboratorSearchAdapter extends RecyclerView.Adapter<Collaborator
holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin())); holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin()));
if(!currentItem.getAvatarUrl().equals("")) { if(!currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.userAvatar); PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.userAvatar);
} }
if(getItemCount() > 0) { if(getItemCount() > 0) {
final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName(); final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName();
Call<Void> call = RetrofitClient Call<Void> call = RetrofitClient.getApiInterface(context).repoCheckCollaborator(repository.getOwner(), repository.getName(), currentItem.getLogin());
.getApiInterface(context)
.repoCheckCollaborator(repository.getOwner(), repository.getName(), currentItem.getLogin());
call.enqueue(new Callback<Void>() { call.enqueue(new Callback<Void>() {
@ -183,4 +122,60 @@ public class CollaboratorSearchAdapter extends RecyclerView.Adapter<Collaborator
public int getItemCount() { public int getItemCount() {
return usersSearchList.size(); return usersSearchList.size();
} }
class CollaboratorSearchViewHolder extends RecyclerView.ViewHolder {
private final ImageView userAvatar;
private final TextView userFullName;
private final TextView userName;
private final ImageView addCollaboratorButtonAdd;
private final ImageView addCollaboratorButtonRemove;
private final String[] permissionList = {"Read", "Write", "Admin"};
final private int permissionSelectedChoice = 0;
private User userInfo;
private CollaboratorSearchViewHolder(View itemView) {
super(itemView);
userAvatar = itemView.findViewById(R.id.userAvatar);
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addCollaboratorButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addCollaboratorButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
addCollaboratorButtonAdd.setOnClickListener(v -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context).setTitle(R.string.newTeamPermission).setSingleChoiceItems(permissionList, permissionSelectedChoice, null)
.setNeutralButton(R.string.cancelButton, null).setPositiveButton(R.string.addButton, (dialog, which) -> {
ListView lw = ((AlertDialog) dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());
CollaboratorActions.addCollaborator(context, String.valueOf(checkedItem).toLowerCase(), userInfo.getLogin(), repository);
});
materialAlertDialogBuilder.create().show();
});
addCollaboratorButtonRemove.setOnClickListener(v -> AlertDialogs.collaboratorRemoveDialog(context, userInfo.getLogin(), repository));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(userInfo.getLogin())) {
userAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userInfo.getLogin());
context.startActivity(intent);
});
userAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin()));
return true;
});
}
}, 500);
}
}
} }

View File

@ -27,31 +27,6 @@ public class CollaboratorsAdapter extends BaseAdapter {
private final List<User> collaboratorsList; private final List<User> collaboratorsList;
private final Context context; private final Context context;
private class ViewHolder {
private String userLoginId;
private final ImageView collaboratorAvatar;
private final TextView collaboratorName;
ViewHolder(View v) {
collaboratorAvatar = v.findViewById(R.id.collaboratorAvatar);
collaboratorName = v.findViewById(R.id.collaboratorName);
collaboratorAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userLoginId);
context.startActivity(intent);
});
collaboratorAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
}
}
public CollaboratorsAdapter(Context ctx, List<User> collaboratorsListMain) { public CollaboratorsAdapter(Context ctx, List<User> collaboratorsListMain) {
this.context = ctx; this.context = ctx;
@ -99,7 +74,8 @@ public class CollaboratorsAdapter extends BaseAdapter {
int imgRadius = AppUtil.getPixelsFromDensity(context, 90); int imgRadius = AppUtil.getPixelsFromDensity(context, 90);
User currentItem = collaboratorsList.get(position); User currentItem = collaboratorsList.get(position);
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop().into(viewHolder.collaboratorAvatar); PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(180, 180).centerCrop()
.into(viewHolder.collaboratorAvatar);
viewHolder.userLoginId = currentItem.getLogin(); viewHolder.userLoginId = currentItem.getLogin();
@ -114,4 +90,29 @@ public class CollaboratorsAdapter extends BaseAdapter {
} }
private class ViewHolder {
private final ImageView collaboratorAvatar;
private final TextView collaboratorName;
private String userLoginId;
ViewHolder(View v) {
collaboratorAvatar = v.findViewById(R.id.collaboratorAvatar);
collaboratorName = v.findViewById(R.id.collaboratorName);
collaboratorAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userLoginId);
context.startActivity(intent);
});
collaboratorAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
}
}
} }

View File

@ -71,6 +71,25 @@ public class CommitsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder
return commitsList.size(); return commitsList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Commit> list) {
commitsList = list;
notifyDataChanged();
}
class CommitsHolder extends RecyclerView.ViewHolder { class CommitsHolder extends RecyclerView.ViewHolder {
View rootView; View rootView;
@ -103,55 +122,44 @@ public class CommitsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder
if(!Objects.equals(commitsModel.getCommit().getCommitter().getEmail(), commitsModel.getCommit().getAuthor().getEmail())) { if(!Objects.equals(commitsModel.getCommit().getCommitter().getEmail(), commitsModel.getCommit().getAuthor().getEmail())) {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(
.getString(R.string.commitAuthoredByAndCommittedByWhen, commitsModel.getCommit().getAuthor().getName(), commitsModel.getCommit().getCommitter().getName(), context.getString(R.string.commitAuthoredByAndCommittedByWhen, commitsModel.getCommit().getAuthor().getName(), commitsModel.getCommit().getCommitter().getName(),
TimeHelper TimeHelper.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty", context)),
.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty", HtmlCompat.FROM_HTML_MODE_COMPACT));
context)), HtmlCompat.FROM_HTML_MODE_COMPACT)); }
} else { else {
commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context commitAuthorAndCommitter.setText(HtmlCompat.fromHtml(context.getString(R.string.commitCommittedByWhen, commitsModel.getCommit().getCommitter().getName(),
.getString(R.string.commitCommittedByWhen, commitsModel.getCommit().getCommitter().getName(), TimeHelper.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty", context)),
TimeHelper HtmlCompat.FROM_HTML_MODE_COMPACT));
.formatTime(TimeHelper.parseIso8601(commitsModel.getCommit().getCommitter().getDate()), context.getResources().getConfiguration().locale, "pretty",
context)), HtmlCompat.FROM_HTML_MODE_COMPACT));
} }
if(commitsModel.getAuthor() != null && commitsModel.getAuthor().getAvatarUrl() != null && if(commitsModel.getAuthor() != null && commitsModel.getAuthor().getAvatarUrl() != null && !commitsModel.getAuthor().getAvatarUrl().isEmpty()) {
!commitsModel.getAuthor().getAvatarUrl().isEmpty()) {
commitAuthorAvatar.setVisibility(View.VISIBLE); commitAuthorAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60); int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(commitsModel.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120)
.load(commitsModel.getAuthor().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop().into(commitAuthorAvatar); .centerCrop().into(commitAuthorAvatar);
} else { }
else {
commitAuthorAvatar.setImageDrawable(null); commitAuthorAvatar.setImageDrawable(null);
commitAuthorAvatar.setVisibility(View.GONE); commitAuthorAvatar.setVisibility(View.GONE);
} }
if(commitsModel.getCommitter() != null && if(commitsModel.getCommitter() != null && (commitsModel.getAuthor() == null || !commitsModel.getAuthor().getLogin().equals(commitsModel.getCommitter().getLogin())) && commitsModel.getCommitter()
(commitsModel.getAuthor() == null || !commitsModel.getAuthor().getLogin().equals(commitsModel.getCommitter().getLogin())) && .getAvatarUrl() != null && !commitsModel.getCommitter().getAvatarUrl().isEmpty()) {
commitsModel.getCommitter().getAvatarUrl() != null &&
!commitsModel.getCommitter().getAvatarUrl().isEmpty()) {
commitCommitterAvatar.setVisibility(View.VISIBLE); commitCommitterAvatar.setVisibility(View.VISIBLE);
int imgRadius = AppUtil.getPixelsFromDensity(context, 60); int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(commitsModel.getCommitter().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120)
.load(commitsModel.getCommitter().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop().into(commitCommitterAvatar); .centerCrop().into(commitCommitterAvatar);
} else { }
else {
commitCommitterAvatar.setImageDrawable(null); commitCommitterAvatar.setImageDrawable(null);
commitCommitterAvatar.setVisibility(View.GONE); commitCommitterAvatar.setVisibility(View.GONE);
} }
@ -161,33 +169,16 @@ public class CommitsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder
Intent intent; Intent intent;
if(context instanceof CommitsActivity) { if(context instanceof CommitsActivity) {
intent = ((CommitsActivity) context).repository.getIntent(context, CommitDetailActivity.class); intent = ((CommitsActivity) context).repository.getIntent(context, CommitDetailActivity.class);
} else { }
intent = IssueContext.fromIntent(((DiffActivity) context).getIntent()).getRepository() else {
.getIntent(context, CommitDetailActivity.class); intent = IssueContext.fromIntent(((DiffActivity) context).getIntent()).getRepository().getIntent(context, CommitDetailActivity.class);
} }
intent.putExtra("sha", commitsModel.getSha()); intent.putExtra("sha", commitsModel.getSha());
context.startActivity(intent); context.startActivity(intent);
}); });
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Commit> list) {
commitsList = list;
notifyDataChanged();
}
} }

View File

@ -23,20 +23,18 @@ import java.util.stream.Collectors;
public class DiffAdapter extends BaseAdapter { public class DiffAdapter extends BaseAdapter {
private final Context context;
private final FragmentManager fragmentManager;
private final List<String> lines;
private final IssueContext issue;
private final List<Integer> selectedLines;
private final Typeface typeface;
private final String type;
private static int COLOR_ADDED; private static int COLOR_ADDED;
private static int COLOR_REMOVED; private static int COLOR_REMOVED;
private static int COLOR_NORMAL; private static int COLOR_NORMAL;
private static int COLOR_SELECTED; private static int COLOR_SELECTED;
private static int COLOR_FONT; private static int COLOR_FONT;
private final Context context;
private final FragmentManager fragmentManager;
private final List<String> lines;
private final IssueContext issue;
private final List<Integer> selectedLines;
private final Typeface typeface;
private final String type;
public DiffAdapter(Context context, FragmentManager fragmentManager, List<String> lines, IssueContext issue, String type) { public DiffAdapter(Context context, FragmentManager fragmentManager, List<String> lines, IssueContext issue, String type) {
@ -149,10 +147,13 @@ public class DiffAdapter extends BaseAdapter {
} }
switch(line.charAt(0)) { switch(line.charAt(0)) {
case '+': return COLOR_ADDED; case '+':
case '-': return COLOR_REMOVED; return COLOR_ADDED;
case '-':
return COLOR_REMOVED;
default: return COLOR_NORMAL; default:
return COLOR_NORMAL;
} }
} }

View File

@ -28,9 +28,9 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
private static final Pattern statisticsPattern = Pattern.compile("(\\d+).*?,.*?(\\d+)"); private static final Pattern statisticsPattern = Pattern.compile("(\\d+).*?,.*?(\\d+)");
private final Context context; private final Context context;
private List<FileDiffView> fileDiffViews;
private final IssueContext issue; private final IssueContext issue;
private final String fragmentType; private final String fragmentType;
private List<FileDiffView> fileDiffViews;
public DiffFilesAdapter(Context context, List<FileDiffView> fileDiffViews, IssueContext issue, String fragmentType) { public DiffFilesAdapter(Context context, List<FileDiffView> fileDiffViews, IssueContext issue, String fragmentType) {
@ -53,53 +53,6 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
((DiffFilesAdapter.FilesHolder) holder).bindData(fileDiffViews.get(position)); ((DiffFilesAdapter.FilesHolder) holder).bindData(fileDiffViews.get(position));
} }
class FilesHolder extends RecyclerView.ViewHolder {
FileDiffView diffFilesObject;
TextView fileName;
TextView fileStatistics;
LinearLayout main_frame;
FilesHolder(View itemView) {
super(itemView);
fileName = itemView.findViewById(R.id.fileName);
fileStatistics = itemView.findViewById(R.id.fileStatistics);
main_frame = itemView.findViewById(R.id.main_frame);
main_frame.setOnClickListener(v -> {
if(fragmentType.equalsIgnoreCase("commit")){
((CommitDetailActivity) context).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, fragmentType))
.commit();
}
else {
((DiffActivity) context).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, issue))
.commit();
}
});
}
void bindData(FileDiffView fileDiffView) {
this.diffFilesObject = fileDiffView;
fileName.setText(fileDiffView.getFileName());
Matcher matcher = statisticsPattern.matcher(fileDiffView.getFileInfo());
if(matcher.find() && matcher.groupCount() == 2) {
fileStatistics.setText(context.getString(R.string.diffStatistics, matcher.group(1), matcher.group(2)));
} else {
fileStatistics.setText(fileDiffView.getFileInfo());
}
}
}
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
return position; return position;
@ -118,4 +71,48 @@ public class DiffFilesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
public void notifyDataChanged() { public void notifyDataChanged() {
notifyDataSetChanged(); notifyDataSetChanged();
} }
class FilesHolder extends RecyclerView.ViewHolder {
FileDiffView diffFilesObject;
TextView fileName;
TextView fileStatistics;
LinearLayout main_frame;
FilesHolder(View itemView) {
super(itemView);
fileName = itemView.findViewById(R.id.fileName);
fileStatistics = itemView.findViewById(R.id.fileStatistics);
main_frame = itemView.findViewById(R.id.main_frame);
main_frame.setOnClickListener(v -> {
if(fragmentType.equalsIgnoreCase("commit")) {
((CommitDetailActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, fragmentType)).commit();
}
else {
((DiffActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, DiffFragment.newInstance(diffFilesObject, issue)).commit();
}
});
}
void bindData(FileDiffView fileDiffView) {
this.diffFilesObject = fileDiffView;
fileName.setText(fileDiffView.getFileName());
Matcher matcher = statisticsPattern.matcher(fileDiffView.getFileInfo());
if(matcher.find() && matcher.groupCount() == 2) {
fileStatistics.setText(context.getString(R.string.diffStatistics, matcher.group(1), matcher.group(2)));
}
else {
fileStatistics.setText(fileDiffView.getFileInfo());
}
}
}
} }

View File

@ -33,17 +33,75 @@ import java.util.List;
public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsViewHolder> { public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsViewHolder> {
private List<DraftWithRepository> draftsList;
private final FragmentManager fragmentManager; private final FragmentManager fragmentManager;
private final Context context; private final Context context;
private List<DraftWithRepository> draftsList;
public DraftsAdapter(Context ctx, FragmentManager fragmentManager, List<DraftWithRepository> draftsListMain) {
this.context = ctx;
this.fragmentManager = fragmentManager;
this.draftsList = draftsListMain;
}
private void deleteDraft(int position) {
draftsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, draftsList.size());
Toasty.success(context, context.getResources().getString(R.string.draftsSingleDeleteSuccess));
}
@NonNull
@Override
public DraftsAdapter.DraftsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_drafts, parent, false);
return new DraftsViewHolder(v);
}
@SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull DraftsAdapter.DraftsViewHolder holder, int position) {
DraftWithRepository currentItem = draftsList.get(position);
String issueNumber = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + currentItem.getIssueId() + "</font>";
Spanned headTitle = HtmlCompat.fromHtml(issueNumber + " " + currentItem.getRepositoryOwner() + " / " + currentItem.getRepositoryName(), HtmlCompat.FROM_HTML_MODE_LEGACY);
holder.repoInfo.setText(headTitle);
holder.draftWithRepository = currentItem;
Markdown.render(context, currentItem.getDraftText(), holder.draftText);
if(!currentItem.getCommentId().equalsIgnoreCase("new")) {
holder.editCommentStatus.setVisibility(View.VISIBLE);
}
else {
holder.editCommentStatus.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return draftsList.size();
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
}
public void updateList(List<DraftWithRepository> list) {
draftsList = list;
notifyDataChanged();
}
class DraftsViewHolder extends RecyclerView.ViewHolder { class DraftsViewHolder extends RecyclerView.ViewHolder {
private DraftWithRepository draftWithRepository;
private final TextView draftText; private final TextView draftText;
private final TextView repoInfo; private final TextView repoInfo;
private final ImageView editCommentStatus; private final ImageView editCommentStatus;
private DraftWithRepository draftWithRepository;
private DraftsViewHolder(View itemView) { private DraftsViewHolder(View itemView) {
@ -83,80 +141,15 @@ public class DraftsAdapter extends RecyclerView.Adapter<DraftsAdapter.DraftsView
BottomSheetReplyFragment bottomSheetReplyFragment = BottomSheetReplyFragment.newInstance(bundle, issue); BottomSheetReplyFragment bottomSheetReplyFragment = BottomSheetReplyFragment.newInstance(bundle, issue);
bottomSheetReplyFragment.setOnInteractedListener(() -> { bottomSheetReplyFragment.setOnInteractedListener(() -> {
Intent i = new IssueContext( Intent i = new IssueContext(new RepositoryContext(draftWithRepository.getRepositoryOwner(), draftWithRepository.getRepositoryName(), context), draftWithRepository.getIssueId(),
new RepositoryContext( draftWithRepository.getIssueType()).getIntent(context, IssueDetailActivity.class);
draftWithRepository.getRepositoryOwner(),
draftWithRepository.getRepositoryName(),
context
),
draftWithRepository.getIssueId(),
draftWithRepository.getIssueType()
).getIntent(context, IssueDetailActivity.class);
i.putExtra("openedFromLink", "true"); i.putExtra("openedFromLink", "true");
context.startActivity(i); context.startActivity(i);
}); });
bottomSheetReplyFragment.show(fragmentManager, "replyBottomSheet"); bottomSheetReplyFragment.show(fragmentManager, "replyBottomSheet");
}); });
} }
} }
public DraftsAdapter(Context ctx, FragmentManager fragmentManager, List<DraftWithRepository> draftsListMain) {
this.context = ctx;
this.fragmentManager = fragmentManager;
this.draftsList = draftsListMain;
}
private void deleteDraft(int position) {
draftsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, draftsList.size());
Toasty.success(context, context.getResources().getString(R.string.draftsSingleDeleteSuccess));
}
@NonNull
@Override
public DraftsAdapter.DraftsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_drafts, parent, false);
return new DraftsViewHolder(v);
}
@SuppressLint("DefaultLocale")
@Override
public void onBindViewHolder(@NonNull DraftsAdapter.DraftsViewHolder holder, int position) {
DraftWithRepository currentItem = draftsList.get(position);
String issueNumber = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + currentItem.getIssueId() + "</font>";
Spanned headTitle = HtmlCompat
.fromHtml(issueNumber + " " + currentItem.getRepositoryOwner() + " / " + currentItem.getRepositoryName(), HtmlCompat.FROM_HTML_MODE_LEGACY);
holder.repoInfo.setText(headTitle);
holder.draftWithRepository = currentItem;
Markdown.render(context, currentItem.getDraftText(), holder.draftText);
if(!currentItem.getCommentId().equalsIgnoreCase("new")) {
holder.editCommentStatus.setVisibility(View.VISIBLE);
}
else {
holder.editCommentStatus.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return draftsList.size();
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
}
public void updateList(List<DraftWithRepository> list) {
draftsList = list;
notifyDataChanged();
}
} }

View File

@ -24,13 +24,7 @@ import org.mian.gitnex.R;
import org.mian.gitnex.activities.IssueDetailActivity; import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
@ -46,10 +40,10 @@ import java.util.Locale;
public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final TinyDB tinyDb;
private List<Issue> searchedList; private List<Issue> searchedList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb;
public ExploreIssuesAdapter(List<Issue> dataList, Context ctx) { public ExploreIssuesAdapter(List<Issue> dataList, Context ctx) {
this.context = ctx; this.context = ctx;
@ -84,9 +78,38 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
return searchedList.size(); return searchedList.size();
} }
class IssuesHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
private Issue issue; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
searchedList = list;
notifyDataChanged();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class IssuesHolder extends RecyclerView.ViewHolder {
private final ImageView issueAssigneeAvatar; private final ImageView issueAssigneeAvatar;
private final TextView issueTitle; private final TextView issueTitle;
@ -96,6 +119,7 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private Issue issue;
IssuesHolder(View itemView) { IssuesHolder(View itemView) {
@ -154,21 +178,16 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
Locale locale = context.getResources().getConfiguration().locale; Locale locale = context.getResources().getConfiguration().locale;
String timeFormat = tinyDb.getString("dateFormat", "pretty"); String timeFormat = tinyDb.getString("dateFormat", "pretty");
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(issue.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(issue.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(issueAssigneeAvatar); .into(issueAssigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + issue.getRepository().getFullName() + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>"; String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + issue.getRepository().getFullName() + context.getResources()
.getString(R.string.hash) + issue.getNumber() + "</font>";
issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + issue.getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY)); issueTitle.setText(HtmlCompat.fromHtml(issueNumber_ + " " + issue.getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY));
issueCommentsCount.setText(String.valueOf(issue.getComments())); issueCommentsCount.setText(String.valueOf(issue.getComments()));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getLabels() != null) { if(issue.getLabels() != null) {
@ -215,9 +234,9 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width( TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
LabelWidthCalculator .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -252,33 +271,7 @@ public class ExploreIssuesAdapter extends RecyclerView.Adapter<RecyclerView.View
} }
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
searchedList = list;
notifyDataChanged();
}
} }

View File

@ -17,11 +17,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -36,10 +32,10 @@ import java.util.Locale;
public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final TinyDB tinyDb;
private List<org.gitnex.tea4j.v2.models.Repository> reposList; private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private Runnable loadMoreListener; private Runnable loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb;
public ExploreRepositoriesAdapter(List<org.gitnex.tea4j.v2.models.Repository> dataList, Context ctx) { public ExploreRepositoriesAdapter(List<org.gitnex.tea4j.v2.models.Repository> dataList, Context ctx) {
this.context = ctx; this.context = ctx;
@ -73,17 +69,36 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
return reposList.size(); return reposList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
class RepositoriesHolder extends RecyclerView.ViewHolder { class RepositoriesHolder extends RecyclerView.ViewHolder {
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private final View spacerView; private final View spacerView;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
RepositoriesHolder(View itemView) { RepositoriesHolder(View itemView) {
super(itemView); super(itemView);
@ -126,7 +141,8 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
if(userRepositories.getAvatarUrl() != null) { if(userRepositories.getAvatarUrl() != null) {
if(!userRepositories.getAvatarUrl().equals("")) { if(!userRepositories.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(userRepositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); PicassoService.getInstance(context).get().load(userRepositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -179,24 +195,7 @@ public class ExploreRepositoriesAdapter extends RecyclerView.Adapter<RecyclerVie
} }
isRepoAdmin.setChecked(userRepositories.getPermissions().isAdmin()); isRepoAdmin.setChecked(userRepositories.getPermissions().isAdmin());
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
} }

View File

@ -4,11 +4,7 @@ import android.content.Context;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Filter; import android.widget.*;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.content.res.AppCompatResources;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@ -30,19 +26,129 @@ public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.FilesViewHol
private final Context context; private final Context context;
private final FilesAdapterListener filesListener; private final FilesAdapterListener filesListener;
private final Filter filesFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<ContentsResponse> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(originalFiles);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(ContentsResponse item : originalFiles) {
if(item.getName().toLowerCase().contains(filterPattern) || item.getPath().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
alteredFiles.clear();
alteredFiles.addAll((List) results.values);
notifyDataSetChanged();
}
};
public FilesAdapter(Context ctx, FilesAdapterListener filesListener) {
this.context = ctx;
this.filesListener = filesListener;
}
public List<ContentsResponse> getOriginalFiles() {
return originalFiles;
}
public void notifyOriginalDataSetChanged() {
alteredFiles.clear();
alteredFiles.addAll(originalFiles);
notifyDataSetChanged();
}
@NonNull
@Override
public FilesAdapter.FilesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_files, parent, false);
return new FilesAdapter.FilesViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull FilesAdapter.FilesViewHolder holder, int position) {
ContentsResponse currentItem = alteredFiles.get(position);
holder.file = currentItem;
holder.fileName.setText(currentItem.getName());
switch(currentItem.getType()) {
case "file":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_file));
holder.fileInfo.setVisibility(View.VISIBLE);
holder.fileInfo.setText(FileUtils.byteCountToDisplaySize(Math.toIntExact(currentItem.getSize())));
break;
case "dir":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_directory));
holder.fileInfo.setVisibility(View.GONE);
break;
case "submodule":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_submodule));
holder.fileInfo.setVisibility(View.GONE);
break;
case "symlink":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_symlink));
holder.fileInfo.setVisibility(View.GONE);
break;
default:
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_question));
}
}
@Override
public int getItemCount() {
return alteredFiles.size();
}
@Override
public Filter getFilter() {
return filesFilter;
}
public interface FilesAdapterListener { public interface FilesAdapterListener {
void onClickFile(ContentsResponse file); void onClickFile(ContentsResponse file);
} }
class FilesViewHolder extends RecyclerView.ViewHolder { class FilesViewHolder extends RecyclerView.ViewHolder {
private ContentsResponse file;
private final ImageView fileTypeIs; private final ImageView fileTypeIs;
private final TextView fileName; private final TextView fileName;
private final TextView fileInfo; private final TextView fileInfo;
private ContentsResponse file;
private FilesViewHolder(View itemView) { private FilesViewHolder(View itemView) {
@ -121,116 +227,7 @@ public class FilesAdapter extends RecyclerView.Adapter<FilesAdapter.FilesViewHol
});*/ });*/
} }
}
public FilesAdapter(Context ctx, FilesAdapterListener filesListener) {
this.context = ctx;
this.filesListener = filesListener;
}
public List<ContentsResponse> getOriginalFiles() {
return originalFiles;
}
public void notifyOriginalDataSetChanged() {
alteredFiles.clear();
alteredFiles.addAll(originalFiles);
notifyDataSetChanged();
}
@NonNull
@Override
public FilesAdapter.FilesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_files, parent, false);
return new FilesAdapter.FilesViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull FilesAdapter.FilesViewHolder holder, int position) {
ContentsResponse currentItem = alteredFiles.get(position);
holder.file = currentItem;
holder.fileName.setText(currentItem.getName());
switch(currentItem.getType()) {
case "file":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_file));
holder.fileInfo.setVisibility(View.VISIBLE);
holder.fileInfo.setText(FileUtils.byteCountToDisplaySize(Math.toIntExact(currentItem.getSize())));
break;
case "dir":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_directory));
holder.fileInfo.setVisibility(View.GONE);
break;
case "submodule":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_submodule));
holder.fileInfo.setVisibility(View.GONE);
break;
case "symlink":
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_symlink));
holder.fileInfo.setVisibility(View.GONE);
break;
default:
holder.fileTypeIs.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_question));
}
}
@Override
public int getItemCount() {
return alteredFiles.size();
}
@Override
public Filter getFilter() {
return filesFilter;
}
private final Filter filesFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<ContentsResponse> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(originalFiles);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (ContentsResponse item : originalFiles) {
if (item.getName().toLowerCase().contains(filterPattern) || item.getPath().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
} }
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
alteredFiles.clear();
alteredFiles.addAll((List) results.values);
notifyDataSetChanged();
}
};
} }

View File

@ -27,13 +27,7 @@ import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.fragments.BottomSheetReplyFragment; import org.mian.gitnex.fragments.BottomSheetReplyFragment;
import org.mian.gitnex.fragments.IssuesFragment; import org.mian.gitnex.fragments.IssuesFragment;
import org.mian.gitnex.helpers.AlertDialogs; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.AppUtil;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.mian.gitnex.views.ReactionList; import org.mian.gitnex.views.ReactionList;
import org.mian.gitnex.views.ReactionSpinner; import org.mian.gitnex.views.ReactionSpinner;
@ -70,16 +64,131 @@ public class IssueCommentsAdapter extends RecyclerView.Adapter<IssueCommentsAdap
this.issue = issue; this.issue = issue;
} }
class IssueCommentViewHolder extends RecyclerView.ViewHolder { private void updateAdapter(int position) {
private String userLoginId; issuesComments.remove(position);
private Comment issueComment; notifyItemRemoved(position);
notifyItemRangeChanged(position, issuesComments.size());
}
private void deleteIssueComment(final Context ctx, final int commentId, int position) {
Call<Void> call = RetrofitClient.getApiInterface(ctx).issueDeleteComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
switch(response.code()) {
case 204:
updateAdapter(position);
Toasty.success(ctx, ctx.getResources().getString(R.string.deleteCommentSuccess));
IssuesFragment.resumeIssues = true;
break;
case 401:
AlertDialogs.authorizationTokenRevokedDialog(ctx);
break;
case 403:
Toasty.error(ctx, ctx.getString(R.string.authorizeError));
break;
case 404:
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
break;
default:
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getResources().getString(R.string.genericServerResponseError));
}
});
}
@NonNull
@Override
public IssueCommentsAdapter.IssueCommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_issue_comments, parent, false);
return new IssueCommentsAdapter.IssueCommentViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull IssueCommentsAdapter.IssueCommentViewHolder holder, int position) {
String timeFormat = tinyDB.getString("dateFormat", "pretty");
Comment issueComment = issuesComments.get(position);
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
holder.userLoginId = issueComment.getUser().getLogin();
holder.issueComment = issueComment;
holder.author.setText(issueComment.getUser().getLogin());
PicassoService.getInstance(context).get().load(issueComment.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0))
.resize(AppUtil.getPixelsFromDensity(context, 35), AppUtil.getPixelsFromDensity(context, 35)).centerCrop().into(holder.avatar);
Markdown.render(context, EmojiParser.parseToUnicode(issueComment.getBody()), holder.comment, issue.getRepository());
StringBuilder informationBuilder = null;
if(issueComment.getCreatedAt() != null) {
if(timeFormat.equals("pretty")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "pretty", context));
holder.information.setOnClickListener(v -> TimeHelper.customDateFormatForToastDateFormat(issueComment.getCreatedAt()));
}
else if(timeFormat.equals("normal")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "normal", context));
}
if(!issueComment.getCreatedAt().equals(issueComment.getUpdatedAt())) {
if(informationBuilder != null) {
informationBuilder.append(context.getString(R.string.colorfulBulletSpan)).append(context.getString(R.string.modifiedText));
}
}
}
holder.information.setText(informationBuilder);
Bundle bundle1 = new Bundle();
bundle1.putAll(bundle);
bundle1.putInt("commentId", Math.toIntExact(issueComment.getId()));
ReactionList reactionList = new ReactionList(context, bundle1);
holder.commentReactionBadges.addView(reactionList);
reactionList.setOnReactionAddedListener(() -> {
if(holder.commentReactionBadges.getVisibility() != View.VISIBLE) {
holder.commentReactionBadges.post(() -> holder.commentReactionBadges.setVisibility(View.VISIBLE));
}
});
}
@Override
public int getItemCount() {
return issuesComments.size();
}
class IssueCommentViewHolder extends RecyclerView.ViewHolder {
private final ImageView avatar; private final ImageView avatar;
private final TextView author; private final TextView author;
private final TextView information; private final TextView information;
private final RecyclerView comment; private final RecyclerView comment;
private final LinearLayout commentReactionBadges; private final LinearLayout commentReactionBadges;
private String userLoginId;
private Comment issueComment;
private IssueCommentViewHolder(View view) { private IssueCommentViewHolder(View view) {
@ -237,128 +346,7 @@ public class IssueCommentsAdapter extends RecyclerView.Adapter<IssueCommentsAdap
} }
}, 500); }, 500);
} }
}
private void updateAdapter(int position) {
issuesComments.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, issuesComments.size());
}
private void deleteIssueComment(final Context ctx, final int commentId, int position) {
Call<Void> call = RetrofitClient
.getApiInterface(ctx)
.issueDeleteComment(issue.getRepository().getOwner(), issue.getRepository().getName(), (long) commentId);
call.enqueue(new Callback<Void>() {
@Override
public void onResponse(@NonNull Call<Void> call, @NonNull retrofit2.Response<Void> response) {
switch(response.code()) {
case 204:
updateAdapter(position);
Toasty.success(ctx, ctx.getResources().getString(R.string.deleteCommentSuccess));
IssuesFragment.resumeIssues = true;
break;
case 401:
AlertDialogs.authorizationTokenRevokedDialog(ctx);
break;
case 403:
Toasty.error(ctx, ctx.getString(R.string.authorizeError));
break;
case 404:
Toasty.warning(ctx, ctx.getString(R.string.apiNotFound));
break;
default:
Toasty.error(ctx, ctx.getString(R.string.genericError));
}
}
@Override
public void onFailure(@NonNull Call<Void> call, @NonNull Throwable t) {
Toasty.error(ctx, ctx.getResources().getString(R.string.genericServerResponseError));
}
});
}
@NonNull
@Override
public IssueCommentsAdapter.IssueCommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_issue_comments, parent, false);
return new IssueCommentsAdapter.IssueCommentViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull IssueCommentsAdapter.IssueCommentViewHolder holder, int position) {
String timeFormat = tinyDB.getString("dateFormat", "pretty");
Comment issueComment = issuesComments.get(position);
int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
holder.userLoginId = issueComment.getUser().getLogin();
holder.issueComment = issueComment;
holder.author.setText(issueComment.getUser().getLogin());
PicassoService.getInstance(context).get()
.load(issueComment.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(AppUtil.getPixelsFromDensity(context, 35), AppUtil.getPixelsFromDensity(context, 35))
.centerCrop()
.into(holder.avatar);
Markdown.render(context, EmojiParser.parseToUnicode(issueComment.getBody()), holder.comment, issue.getRepository());
StringBuilder informationBuilder = null;
if(issueComment.getCreatedAt() != null) {
if(timeFormat.equals("pretty")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "pretty", context));
holder.information.setOnClickListener(v -> TimeHelper.customDateFormatForToastDateFormat(issueComment.getCreatedAt()));
}
else if(timeFormat.equals("normal")) {
informationBuilder = new StringBuilder(TimeHelper.formatTime(issueComment.getCreatedAt(), locale, "normal", context));
}
if(!issueComment.getCreatedAt().equals(issueComment.getUpdatedAt())) {
if(informationBuilder != null) {
informationBuilder.append(context.getString(R.string.colorfulBulletSpan)).append(context.getString(R.string.modifiedText));
}
}
}
holder.information.setText(informationBuilder);
Bundle bundle1 = new Bundle();
bundle1.putAll(bundle);
bundle1.putInt("commentId", Math.toIntExact(issueComment.getId()));
ReactionList reactionList = new ReactionList(context, bundle1);
holder.commentReactionBadges.addView(reactionList);
reactionList.setOnReactionAddedListener(() -> {
if(holder.commentReactionBadges.getVisibility() != View.VISIBLE) {
holder.commentReactionBadges.post(() -> holder.commentReactionBadges.setVisibility(View.VISIBLE));
}
});
} }
@Override
public int getItemCount() {
return issuesComments.size();
}
} }

View File

@ -26,13 +26,7 @@ import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -47,10 +41,10 @@ import java.util.Locale;
public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
TinyDB tinyDb;
private List<Issue> issuesList; private List<Issue> issuesList;
private Runnable loadMoreListener; private Runnable loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
TinyDB tinyDb;
public IssuesAdapter(Context ctx, List<Issue> issuesListMain) { public IssuesAdapter(Context ctx, List<Issue> issuesListMain) {
@ -88,9 +82,26 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
return issuesList.size(); return issuesList.size();
} }
class IssuesHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private Issue issueObject; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
issuesList = list;
notifyDataChanged();
}
class IssuesHolder extends RecyclerView.ViewHolder {
private final ImageView issueAssigneeAvatar; private final ImageView issueAssigneeAvatar;
private final TextView issueTitle; private final TextView issueTitle;
@ -100,6 +111,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private Issue issueObject;
IssuesHolder(View itemView) { IssuesHolder(View itemView) {
@ -138,12 +150,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
int imgRadius = AppUtil.getPixelsFromDensity(context, 3); int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(issue.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(issue.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(issueAssigneeAvatar); .into(issueAssigneeAvatar);
String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>"; String issueNumber_ = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + issue.getNumber() + "</font>";
@ -158,8 +165,7 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
frameLabels.setOnClickListener(v -> context.startActivity(intentIssueDetail)); frameLabels.setOnClickListener(v -> context.startActivity(intentIssueDetail));
frameLabelsDots.setOnClickListener(v -> context.startActivity(intentIssueDetail)); frameLabelsDots.setOnClickListener(v -> context.startActivity(intentIssueDetail));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(issue.getLabels() != null) { if(issue.getLabels() != null) {
@ -206,8 +212,9 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width(LabelWidthCalculator TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -241,22 +248,4 @@ public class IssuesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Issue> list) {
issuesList = list;
notifyDataChanged();
}
} }

View File

@ -35,76 +35,6 @@ public class LabelsAdapter extends RecyclerView.Adapter<LabelsAdapter.LabelsView
private final String type; private final String type;
private final String orgName; private final String orgName;
class LabelsViewHolder extends RecyclerView.ViewHolder {
private Label labels;
private final MaterialCardView labelView;
private final ImageView labelIcon;
private final TextView labelName;
private LabelsViewHolder(View itemView) {
super(itemView);
labelView = itemView.findViewById(R.id.labelView);
labelIcon = itemView.findViewById(R.id.labelIcon);
labelName = itemView.findViewById(R.id.labelName);
ImageView labelsOptionsMenu = itemView.findViewById(R.id.labelsOptionsMenu);
if((type.equals("repo") && !((RepoDetailActivity) itemView.getContext()).repository.getPermissions().isPush()) ||
(type.equals("org") && (((OrganizationDetailActivity) itemView.getContext()).permissions == null || !((OrganizationDetailActivity) itemView.getContext()).permissions.isIsOwner()))) {
labelsOptionsMenu.setVisibility(View.GONE);
}
labelsOptionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams")
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_labels_in_list, null);
TextView labelMenuEdit = view.findViewById(R.id.labelMenuEdit);
TextView labelMenuDelete = view.findViewById(R.id.labelMenuDelete);
TextView bottomSheetHeader = view.findViewById(R.id.bottomSheetHeader);
bottomSheetHeader.setText(labels.getName());
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
labelMenuEdit.setOnClickListener(editLabel -> {
Intent intent = new Intent(context, CreateLabelActivity.class);
intent.putExtra("labelId", String.valueOf(labels.getId()));
intent.putExtra("labelTitle", labels.getName());
intent.putExtra("labelColor", labels.getColor());
intent.putExtra("labelAction", "edit");
intent.putExtra("type", type);
intent.putExtra("orgName", orgName);
if(type.equals("repo")) {
intent.putExtra(RepositoryContext.INTENT_EXTRA, ((RepoDetailActivity) itemView.getContext()).repository);
}
context.startActivity(intent);
dialog.dismiss();
});
labelMenuDelete.setOnClickListener(deleteLabel -> {
RepositoryContext repo;
if(type.equals("repo")) {
repo = ((RepoDetailActivity) itemView.getContext()).repository;
} else {
repo = null;
}
AlertDialogs.labelDeleteDialog(context, labels.getName(), String.valueOf(labels.getId()),
type, orgName, repo);
dialog.dismiss();
});
});
}
}
public LabelsAdapter(Context ctx, List<Label> labelsMain, String type, String orgName) { public LabelsAdapter(Context ctx, List<Label> labelsMain, String type, String orgName) {
this.labelsList = labelsMain; this.labelsList = labelsMain;
@ -147,4 +77,74 @@ public class LabelsAdapter extends RecyclerView.Adapter<LabelsAdapter.LabelsView
public void notifyDataChanged() { public void notifyDataChanged() {
notifyDataSetChanged(); notifyDataSetChanged();
} }
class LabelsViewHolder extends RecyclerView.ViewHolder {
private final MaterialCardView labelView;
private final ImageView labelIcon;
private final TextView labelName;
private Label labels;
private LabelsViewHolder(View itemView) {
super(itemView);
labelView = itemView.findViewById(R.id.labelView);
labelIcon = itemView.findViewById(R.id.labelIcon);
labelName = itemView.findViewById(R.id.labelName);
ImageView labelsOptionsMenu = itemView.findViewById(R.id.labelsOptionsMenu);
if((type.equals("repo") && !((RepoDetailActivity) itemView.getContext()).repository.getPermissions().isPush()) || (type.equals(
"org") && (((OrganizationDetailActivity) itemView.getContext()).permissions == null || !((OrganizationDetailActivity) itemView.getContext()).permissions.isIsOwner()))) {
labelsOptionsMenu.setVisibility(View.GONE);
}
labelsOptionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_labels_in_list, null);
TextView labelMenuEdit = view.findViewById(R.id.labelMenuEdit);
TextView labelMenuDelete = view.findViewById(R.id.labelMenuDelete);
TextView bottomSheetHeader = view.findViewById(R.id.bottomSheetHeader);
bottomSheetHeader.setText(labels.getName());
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
labelMenuEdit.setOnClickListener(editLabel -> {
Intent intent = new Intent(context, CreateLabelActivity.class);
intent.putExtra("labelId", String.valueOf(labels.getId()));
intent.putExtra("labelTitle", labels.getName());
intent.putExtra("labelColor", labels.getColor());
intent.putExtra("labelAction", "edit");
intent.putExtra("type", type);
intent.putExtra("orgName", orgName);
if(type.equals("repo")) {
intent.putExtra(RepositoryContext.INTENT_EXTRA, ((RepoDetailActivity) itemView.getContext()).repository);
}
context.startActivity(intent);
dialog.dismiss();
});
labelMenuDelete.setOnClickListener(deleteLabel -> {
RepositoryContext repo;
if(type.equals("repo")) {
repo = ((RepoDetailActivity) itemView.getContext()).repository;
}
else {
repo = null;
}
AlertDialogs.labelDeleteDialog(context, labels.getName(), String.valueOf(labels.getId()), type, orgName, repo);
dialog.dismiss();
});
});
}
}
} }

View File

@ -21,18 +21,11 @@ import java.util.List;
public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.LabelsViewHolder> { public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.LabelsViewHolder> {
private List<Integer> currentLabelsIds;
private final List<Label> labels; private final List<Label> labels;
private final List<String> labelsStrings = new ArrayList<>(); private final List<String> labelsStrings = new ArrayList<>();
private List<Integer> labelsIds = new ArrayList<>();
private final LabelsListAdapterListener labelsListener; private final LabelsListAdapterListener labelsListener;
private List<Integer> currentLabelsIds;
public interface LabelsListAdapterListener { private List<Integer> labelsIds = new ArrayList<>();
void labelsInterface(List<String> data);
void labelsIdsInterface(List<Integer> data);
}
public LabelsListAdapter(List<Label> labelsMain, LabelsListAdapterListener labelsListener, List<Integer> currentLabelsIds) { public LabelsListAdapter(List<Label> labelsMain, LabelsListAdapterListener labelsListener, List<Integer> currentLabelsIds) {
@ -41,23 +34,6 @@ public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.La
this.currentLabelsIds = currentLabelsIds; this.currentLabelsIds = currentLabelsIds;
} }
static class LabelsViewHolder extends RecyclerView.ViewHolder {
private final CheckBox labelSelection;
private final TextView labelText;
private final ImageView labelColor;
private LabelsViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
labelSelection = itemView.findViewById(R.id.labelSelection);
labelText = itemView.findViewById(R.id.labelText);
labelColor = itemView.findViewById(R.id.labelColor);
}
}
@NonNull @NonNull
@Override @Override
public LabelsListAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public LabelsListAdapter.LabelsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -129,4 +105,31 @@ public class LabelsListAdapter extends RecyclerView.Adapter<LabelsListAdapter.La
currentLabelsIds = list; currentLabelsIds = list;
notifyDataSetChanged(); notifyDataSetChanged();
} }
public interface LabelsListAdapterListener {
void labelsInterface(List<String> data);
void labelsIdsInterface(List<Integer> data);
}
static class LabelsViewHolder extends RecyclerView.ViewHolder {
private final CheckBox labelSelection;
private final TextView labelText;
private final ImageView labelColor;
private LabelsViewHolder(View itemView) {
super(itemView);
this.setIsRecyclable(false);
labelSelection = itemView.findViewById(R.id.labelSelection);
labelText = itemView.findViewById(R.id.labelText);
labelColor = itemView.findViewById(R.id.labelColor);
}
}
} }

View File

@ -35,10 +35,10 @@ import java.util.Locale;
public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final RepositoryContext repository;
private List<Milestone> dataList; private List<Milestone> dataList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
private final RepositoryContext repository;
public MilestonesAdapter(Context ctx, List<Milestone> dataListMain, RepositoryContext repository) { public MilestonesAdapter(Context ctx, List<Milestone> dataListMain, RepositoryContext repository) {
this.repository = repository; this.repository = repository;
@ -64,9 +64,54 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
((MilestonesAdapter.DataHolder) holder).bindData(dataList.get(position)); ((MilestonesAdapter.DataHolder) holder).bindData(dataList.get(position));
} }
class DataHolder extends RecyclerView.ViewHolder { @Override
public int getItemViewType(int position) {
return position;
}
private Milestone milestones; @Override
public int getItemCount() {
return dataList.size();
}
private void updateAdapter(int position) {
dataList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, dataList.size());
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Milestone> list) {
dataList = list;
notifyDataChanged();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class DataHolder extends RecyclerView.ViewHolder {
private final TextView msTitle; private final TextView msTitle;
private final TextView msDescription; private final TextView msDescription;
@ -74,6 +119,7 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
private final TextView msClosedIssues; private final TextView msClosedIssues;
private final TextView msDueDate; private final TextView msDueDate;
private final ProgressBar msProgress; private final ProgressBar msProgress;
private Milestone milestones;
DataHolder(View itemView) { DataHolder(View itemView) {
@ -211,49 +257,7 @@ public class MilestonesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
msDueDate.setText(context.getString(R.string.milestoneNoDueDate)); msDueDate.setText(context.getString(R.string.milestoneNoDueDate));
} }
} }
} }
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return dataList.size();
}
private void updateAdapter(int position) {
dataList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, dataList.size());
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Milestone> list) {
dataList = list;
notifyDataChanged();
}
} }

View File

@ -28,34 +28,6 @@ public class MostVisitedReposAdapter extends RecyclerView.Adapter<MostVisitedRep
private List<Repository> mostVisitedReposList; private List<Repository> mostVisitedReposList;
static class MostVisitedViewHolder extends RecyclerView.ViewHolder {
private Repository repository;
private final ImageView image;
private final TextView repoName;
private final TextView orgName;
private final TextView mostVisited;
private MostVisitedViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
repoName = itemView.findViewById(R.id.repo_name);
orgName = itemView.findViewById(R.id.org_name);
mostVisited = itemView.findViewById(R.id.most_visited);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
RepositoryContext repositoryContext = new RepositoryContext(repository.getRepositoryOwner(), repository.getRepositoryName(), context);
Intent intent = repositoryContext.getIntent(context, RepoDetailActivity.class);
context.startActivity(intent);
});
}
}
public MostVisitedReposAdapter(List<Repository> reposListMain) { public MostVisitedReposAdapter(List<Repository> reposListMain) {
this.mostVisitedReposList = reposListMain; this.mostVisitedReposList = reposListMain;
} }
@ -100,4 +72,33 @@ public class MostVisitedReposAdapter extends RecyclerView.Adapter<MostVisitedRep
mostVisitedReposList = list; mostVisitedReposList = list;
notifyDataChanged(); notifyDataChanged();
} }
static class MostVisitedViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView repoName;
private final TextView orgName;
private final TextView mostVisited;
private Repository repository;
private MostVisitedViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
repoName = itemView.findViewById(R.id.repo_name);
orgName = itemView.findViewById(R.id.org_name);
mostVisited = itemView.findViewById(R.id.most_visited);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
RepositoryContext repositoryContext = new RepositoryContext(repository.getRepositoryOwner(), repository.getRepositoryName(), context);
Intent intent = repositoryContext.getIntent(context, RepoDetailActivity.class);
context.startActivity(intent);
});
}
}
} }

View File

@ -23,20 +23,6 @@ public class MyProfileEmailsAdapter extends RecyclerView.Adapter<MyProfileEmails
private final List<Email> emailsList; private final List<Email> emailsList;
private final Context context; private final Context context;
static class EmailsViewHolder extends RecyclerView.ViewHolder {
private final ImageView emailPrimary;
private final TextView userEmail;
private EmailsViewHolder(View itemView) {
super(itemView);
emailPrimary = itemView.findViewById(R.id.emailPrimary);
userEmail = itemView.findViewById(R.id.userEmail);
}
}
public MyProfileEmailsAdapter(Context ctx, List<Email> emailsListMain) { public MyProfileEmailsAdapter(Context ctx, List<Email> emailsListMain) {
this.context = ctx; this.context = ctx;
this.emailsList = emailsListMain; this.emailsList = emailsListMain;
@ -57,13 +43,7 @@ public class MyProfileEmailsAdapter extends RecyclerView.Adapter<MyProfileEmails
holder.userEmail.setText(currentItem.getEmail()); holder.userEmail.setText(currentItem.getEmail());
if(currentItem.isPrimary()) { if(currentItem.isPrimary()) {
TextDrawable drawable = TextDrawable.builder() TextDrawable drawable = TextDrawable.builder().beginConfig().textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null)).fontSize(36).width(220).height(60).endConfig()
.beginConfig()
.textColor(ResourcesCompat.getColor(context.getResources(), R.color.colorWhite, null))
.fontSize(36)
.width(220)
.height(60)
.endConfig()
.buildRoundRect(context.getResources().getString(R.string.emailTypeText), ResourcesCompat.getColor(context.getResources(), R.color.tooltipBackground, null), 8); .buildRoundRect(context.getResources().getString(R.string.emailTypeText), ResourcesCompat.getColor(context.getResources(), R.color.tooltipBackground, null), 8);
holder.emailPrimary.setImageDrawable(drawable); holder.emailPrimary.setImageDrawable(drawable);
} }
@ -78,4 +58,19 @@ public class MyProfileEmailsAdapter extends RecyclerView.Adapter<MyProfileEmails
return emailsList.size(); return emailsList.size();
} }
static class EmailsViewHolder extends RecyclerView.ViewHolder {
private final ImageView emailPrimary;
private final TextView userEmail;
private EmailsViewHolder(View itemView) {
super(itemView);
emailPrimary = itemView.findViewById(R.id.emailPrimary);
userEmail = itemView.findViewById(R.id.userEmail);
}
}
} }

View File

@ -27,9 +27,9 @@ import java.util.List;
public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private List<NotificationThread> notificationThreads;
private final OnMoreClickedListener onMoreClickedListener; private final OnMoreClickedListener onMoreClickedListener;
private final OnNotificationClickedListener onNotificationClickedListener; private final OnNotificationClickedListener onNotificationClickedListener;
private List<NotificationThread> notificationThreads;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
public NotificationsAdapter(Context context, List<NotificationThread> notificationThreads, OnMoreClickedListener onMoreClickedListener, OnNotificationClickedListener onNotificationClickedListener) { public NotificationsAdapter(Context context, List<NotificationThread> notificationThreads, OnMoreClickedListener onMoreClickedListener, OnNotificationClickedListener onNotificationClickedListener) {
@ -65,14 +65,41 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
return notificationThreads.size(); return notificationThreads.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void updateList(List<NotificationThread> list) {
notificationThreads = list;
notifyDataChanged();
}
public interface OnNotificationClickedListener {
void onNotificationClicked(NotificationThread notificationThread);
}
public interface OnMoreClickedListener {
void onMoreClicked(NotificationThread notificationThread);
}
class NotificationsHolder extends RecyclerView.ViewHolder { class NotificationsHolder extends RecyclerView.ViewHolder {
private final LinearLayout frame; private final LinearLayout frame;
private final TextView subject; private final TextView subject;
private final TextView repository; private final TextView repository;
private final ImageView type; private final ImageView type;
private ImageView pinned;
private final ImageView more; private final ImageView more;
private ImageView pinned;
NotificationsHolder(View itemView) { NotificationsHolder(View itemView) {
@ -92,13 +119,15 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
String subjectId = ""; String subjectId = "";
if(StringUtils.containsAny(notificationThread.getSubject().getType().toLowerCase(), "pull", "issue")) { if(StringUtils.containsAny(notificationThread.getSubject().getType().toLowerCase(), "pull", "issue")) {
subjectId = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + url.substring(url.lastIndexOf("/") + 1) + "</font>"; subjectId = "<font color='" + ResourcesCompat.getColor(context.getResources(), R.color.lightGray, null) + "'>" + context.getResources().getString(R.string.hash) + url.substring(
url.lastIndexOf("/") + 1) + "</font>";
} }
subject.setText(HtmlCompat.fromHtml(subjectId + " " + notificationThread.getSubject().getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY)); subject.setText(HtmlCompat.fromHtml(subjectId + " " + notificationThread.getSubject().getTitle(), HtmlCompat.FROM_HTML_MODE_LEGACY));
if(!notificationThread.getSubject().getType().equalsIgnoreCase("repository")) { if(!notificationThread.getSubject().getType().equalsIgnoreCase("repository")) {
repository.setText(notificationThread.getRepository().getFullName()); repository.setText(notificationThread.getRepository().getFullName());
} else { }
else {
repository.setVisibility(View.GONE); repository.setVisibility(View.GONE);
pinned.setVisibility(View.GONE); pinned.setVisibility(View.GONE);
pinned = itemView.findViewById(R.id.pinnedVertical); pinned = itemView.findViewById(R.id.pinnedVertical);
@ -151,28 +180,7 @@ public class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.View
more.setOnClickListener(v -> onMoreClickedListener.onMoreClicked(notificationThread)); more.setOnClickListener(v -> onMoreClickedListener.onMoreClicked(notificationThread));
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void updateList(List<NotificationThread> list) {
notificationThreads = list;
notifyDataChanged();
}
public interface OnNotificationClickedListener {
void onNotificationClicked(NotificationThread notificationThread);
}
public interface OnMoreClickedListener {
void onMoreClicked(NotificationThread notificationThread);
}
} }

View File

@ -28,121 +28,10 @@ import java.util.List;
public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final Context context; private final Context context;
private List<Organization> orgList;
private final List<Organization> orgListFull; private final List<Organization> orgListFull;
private List<Organization> orgList;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
public OrganizationsListAdapter(Context ctx, List<Organization> orgListMain) {
this.context = ctx;
this.orgList = orgListMain;
orgListFull = new ArrayList<>(orgList);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
return new OrganizationsListAdapter.OrgHolder(inflater.inflate(R.layout.list_organizations, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
((OrganizationsListAdapter.OrgHolder) holder).bindData(orgList.get(position));
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return orgList.size();
}
class OrgHolder extends RecyclerView.ViewHolder {
private Organization userOrganizations;
private final ImageView image;
private final TextView orgName;
private final TextView orgDescription;
OrgHolder(View itemView) {
super(itemView);
orgName = itemView.findViewById(R.id.orgName);
orgDescription = itemView.findViewById(R.id.orgDescription);
image = itemView.findViewById(R.id.imageAvatar);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationDetailActivity.class);
intent.putExtra("orgName", userOrganizations.getUsername());
context.startActivity(intent);
});
}
void bindData(Organization org) {
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
this.userOrganizations = org;
orgName.setText(org.getUsername());
PicassoService.getInstance(context).get().load(org.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image);
if(!org.getDescription().equals("")) {
orgDescription.setVisibility(View.VISIBLE);
orgDescription.setText(org.getDescription());
}
else {
orgDescription.setVisibility(View.GONE);
}
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public abstract static class OnLoadMoreListener {
protected abstract void onLoadMore();
public void onLoadFinished() {}
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Organization> list) {
orgList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return orgFilter;
}
private final Filter orgFilter = new Filter() { private final Filter orgFilter = new Filter() {
@Override @Override
@ -179,4 +68,117 @@ public class OrganizationsListAdapter extends RecyclerView.Adapter<RecyclerView.
notifyDataChanged(); notifyDataChanged();
} }
}; };
public OrganizationsListAdapter(Context ctx, List<Organization> orgListMain) {
this.context = ctx;
this.orgList = orgListMain;
orgListFull = new ArrayList<>(orgList);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
return new OrganizationsListAdapter.OrgHolder(inflater.inflate(R.layout.list_organizations, parent, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if(position >= getItemCount() - 1 && isMoreDataAvailable && !isLoading && loadMoreListener != null) {
isLoading = true;
loadMoreListener.onLoadMore();
}
((OrganizationsListAdapter.OrgHolder) holder).bindData(orgList.get(position));
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getItemCount() {
return orgList.size();
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<Organization> list) {
orgList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return orgFilter;
}
public abstract static class OnLoadMoreListener {
protected abstract void onLoadMore();
public void onLoadFinished() {
}
}
class OrgHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView orgName;
private final TextView orgDescription;
private Organization userOrganizations;
OrgHolder(View itemView) {
super(itemView);
orgName = itemView.findViewById(R.id.orgName);
orgDescription = itemView.findViewById(R.id.orgDescription);
image = itemView.findViewById(R.id.imageAvatar);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationDetailActivity.class);
intent.putExtra("orgName", userOrganizations.getUsername());
context.startActivity(intent);
});
}
void bindData(Organization org) {
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
this.userOrganizations = org;
orgName.setText(org.getUsername());
PicassoService.getInstance(context).get().load(org.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image);
if(!org.getDescription().equals("")) {
orgDescription.setVisibility(View.VISIBLE);
orgDescription.setText(org.getDescription());
}
else {
orgDescription.setVisibility(View.GONE);
}
}
}
} }

View File

@ -26,13 +26,7 @@ import org.mian.gitnex.activities.IssueDetailActivity;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.ColorInverter;
import org.mian.gitnex.helpers.LabelWidthCalculator;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.IssueContext; import org.mian.gitnex.helpers.contexts.IssueContext;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -80,9 +74,26 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
return prList.size(); return prList.size();
} }
class PullRequestsHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private PullRequest pullRequestObject; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<PullRequest> list) {
prList = list;
notifyDataChanged();
}
class PullRequestsHolder extends RecyclerView.ViewHolder {
private final ImageView assigneeAvatar; private final ImageView assigneeAvatar;
private final TextView prTitle; private final TextView prTitle;
@ -92,6 +103,7 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
private final LinearLayout frameLabels; private final LinearLayout frameLabels;
private final HorizontalScrollView labelsScrollViewDots; private final HorizontalScrollView labelsScrollViewDots;
private final LinearLayout frameLabelsDots; private final LinearLayout frameLabelsDots;
private PullRequest pullRequestObject;
PullRequestsHolder(View itemView) { PullRequestsHolder(View itemView) {
@ -139,18 +151,12 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
String timeFormat = tinyDb.getString("dateFormat", "pretty"); String timeFormat = tinyDb.getString("dateFormat", "pretty");
int imgRadius = AppUtil.getPixelsFromDensity(context, 3); int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(pullRequest.getUser().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(pullRequest.getUser().getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(this.assigneeAvatar); .into(this.assigneeAvatar);
this.pullRequestObject = pullRequest; this.pullRequestObject = pullRequest;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 15, 0); params.setMargins(0, 0, 15, 0);
if(pullRequest.getLabels() != null) { if(pullRequest.getLabels() != null) {
@ -197,8 +203,9 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
int height = AppUtil.getPixelsFromDensity(context, 20); int height = AppUtil.getPixelsFromDensity(context, 20);
int textSize = AppUtil.getPixelsFromScaledDensity(context, 12); int textSize = AppUtil.getPixelsFromScaledDensity(context, 12);
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize).width(LabelWidthCalculator TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).textColor(new ColorInverter().getContrastColor(color)).fontSize(textSize)
.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig().buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18)); .width(LabelWidthCalculator.calculateLabelWidth(labelName, Typeface.DEFAULT, textSize, AppUtil.getPixelsFromDensity(context, 8))).height(height).endConfig()
.buildRoundRect(labelName, color, AppUtil.getPixelsFromDensity(context, 18));
labelsView.setImageDrawable(drawable); labelsView.setImageDrawable(drawable);
frameLabels.addView(labelsView); frameLabels.addView(labelsView);
@ -220,24 +227,7 @@ public class PullRequestsAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
this.prCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(pullRequest.getCreatedAt()), context)); this.prCreatedTime.setOnClickListener(new ClickListener(TimeHelper.customDateFormatForToastDateFormat(pullRequest.getCreatedAt()), context));
} }
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<PullRequest> list) {
prList = list;
notifyDataChanged();
}
} }

View File

@ -39,16 +39,13 @@ public class ReactionAuthorsAdapter extends RecyclerView.Adapter<ReactionAuthors
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User userInfo = userInfos.get(position); User userInfo = userInfos.get(position);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).resize(240, 240).transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 6), 0))
.load(userInfo.getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.resize(240, 240)
.transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 6), 0))
.centerCrop().into(holder.authorAvatar); .centerCrop().into(holder.authorAvatar);
if(userInfo.getFullName() == null || userInfo.getFullName().isEmpty()) { if(userInfo.getFullName() == null || userInfo.getFullName().isEmpty()) {
holder.authorFullName.setVisibility(View.GONE); holder.authorFullName.setVisibility(View.GONE);
} else { }
else {
holder.authorFullName.setText(userInfo.getFullName()); holder.authorFullName.setText(userInfo.getFullName());
holder.authorFullName.setVisibility(View.VISIBLE); holder.authorFullName.setVisibility(View.VISIBLE);
} }
@ -75,6 +72,7 @@ public class ReactionAuthorsAdapter extends RecyclerView.Adapter<ReactionAuthors
authorFullName = itemView.findViewById(R.id.authorFullName); authorFullName = itemView.findViewById(R.id.authorFullName);
authorLogin = itemView.findViewById(R.id.authorLogin); authorLogin = itemView.findViewById(R.id.authorLogin);
} }
} }
} }

View File

@ -23,13 +23,7 @@ import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.clients.RetrofitClient; import org.mian.gitnex.clients.RetrofitClient;
import org.mian.gitnex.databinding.FragmentReleasesBinding; import org.mian.gitnex.databinding.FragmentReleasesBinding;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.Markdown;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.Toasty;
import org.mian.gitnex.structs.FragmentRefreshListener; import org.mian.gitnex.structs.FragmentRefreshListener;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -43,89 +37,14 @@ import retrofit2.Response;
public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.ReleasesViewHolder> { public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.ReleasesViewHolder> {
private List<Release> releasesList;
private final Context context; private final Context context;
private final String repoOwner; private final String repoOwner;
private final String repoName; private final String repoName;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
private final FragmentReleasesBinding fragmentReleasesBinding; private final FragmentReleasesBinding fragmentReleasesBinding;
private List<Release> releasesList;
protected class ReleasesViewHolder extends RecyclerView.ViewHolder { private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private Release releases;
private final TextView releaseType;
private final TextView releaseName;
private final ImageView authorAvatar;
private final TextView authorName;
private final TextView releaseTag;
private final TextView releaseDate;
private final TextView releaseBodyContent;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final RecyclerView downloadList;
private final ImageView optionsMenu;
private ReleasesViewHolder(View itemView) {
super(itemView);
releaseType = itemView.findViewById(R.id.releaseType);
releaseName = itemView.findViewById(R.id.releaseName);
authorAvatar = itemView.findViewById(R.id.authorAvatar);
authorName = itemView.findViewById(R.id.authorName);
releaseTag = itemView.findViewById(R.id.releaseTag);
TextView releaseCommitSha = itemView.findViewById(R.id.releaseCommitSha);
releaseDate = itemView.findViewById(R.id.releaseDate);
releaseBodyContent = itemView.findViewById(R.id.releaseBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
downloadList = itemView.findViewById(R.id.downloadList);
optionsMenu = itemView.findViewById(R.id.releasesOptionsMenu);
downloadList.setHasFixedSize(true);
downloadList.setLayoutManager(new LinearLayoutManager(itemView.getContext()));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(releases.getAuthor().getLogin())) {
authorAvatar.setOnClickListener(loginId -> {
Context context = loginId.getContext();
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", releases.getAuthor().getLogin());
context.startActivity(intent);
});
}
}, 500);
optionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_release_in_list, itemView.findViewById(android.R.id.content), false);
TextView deleteRelease = view.findViewById(R.id.deleteRelease);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
deleteRelease.setOnClickListener(v1 -> {
deleteRelease(context, releases.getName(), releases.getId(), repoOwner, repoName, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
public ReleasesAdapter(Context ctx, List<Release> releasesMain, FragmentRefreshListener startDownload, String repoOwner, String repoName, FragmentReleasesBinding fragmentReleasesBinding) { public ReleasesAdapter(Context ctx, List<Release> releasesMain, FragmentRefreshListener startDownload, String repoOwner, String repoName, FragmentReleasesBinding fragmentReleasesBinding) {
this.context = ctx; this.context = ctx;
@ -170,7 +89,8 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
} }
if(currentItem.getAuthor().getAvatarUrl() != null) { if(currentItem.getAuthor().getAvatarUrl() != null) {
PicassoService.getInstance(context).get().load(currentItem.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.authorAvatar); PicassoService.getInstance(context).get().load(currentItem.getAuthor().getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.authorAvatar);
} }
holder.authorName.setText(context.getResources().getString(R.string.releasePublishedBy, currentItem.getAuthor().getLogin())); holder.authorName.setText(context.getResources().getString(R.string.releasePublishedBy, currentItem.getAuthor().getLogin()));
@ -244,12 +164,6 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
loadMoreListener.onLoadFinished(); loadMoreListener.onLoadFinished();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) { public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener; this.loadMoreListener = loadMoreListener;
} }
@ -269,10 +183,8 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Material3_Dialog_Alert); MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Material3_Dialog_Alert);
materialAlertDialogBuilder.setTitle(String.format(context.getString(R.string.deleteGenericTitle), releaseName)) materialAlertDialogBuilder.setTitle(String.format(context.getString(R.string.deleteGenericTitle), releaseName)).setMessage(R.string.deleteReleaseConfirmation)
.setMessage(R.string.deleteReleaseConfirmation) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(context).repoDeleteRelease(owner, repo, releaseId).enqueue(new Callback<>() {
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(context).repoDeleteRelease(owner, repo, releaseId).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
@ -298,7 +210,89 @@ public class ReleasesAdapter extends RecyclerView.Adapter<ReleasesAdapter.Releas
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
})) })).setNeutralButton(R.string.cancelButton, null).show();
.setNeutralButton(R.string.cancelButton, null).show();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
protected class ReleasesViewHolder extends RecyclerView.ViewHolder {
private final TextView releaseType;
private final TextView releaseName;
private final ImageView authorAvatar;
private final TextView authorName;
private final TextView releaseTag;
private final TextView releaseDate;
private final TextView releaseBodyContent;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final RecyclerView downloadList;
private final ImageView optionsMenu;
private Release releases;
private ReleasesViewHolder(View itemView) {
super(itemView);
releaseType = itemView.findViewById(R.id.releaseType);
releaseName = itemView.findViewById(R.id.releaseName);
authorAvatar = itemView.findViewById(R.id.authorAvatar);
authorName = itemView.findViewById(R.id.authorName);
releaseTag = itemView.findViewById(R.id.releaseTag);
TextView releaseCommitSha = itemView.findViewById(R.id.releaseCommitSha);
releaseDate = itemView.findViewById(R.id.releaseDate);
releaseBodyContent = itemView.findViewById(R.id.releaseBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
downloadList = itemView.findViewById(R.id.downloadList);
optionsMenu = itemView.findViewById(R.id.releasesOptionsMenu);
downloadList.setHasFixedSize(true);
downloadList.setLayoutManager(new LinearLayoutManager(itemView.getContext()));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(releases.getAuthor().getLogin())) {
authorAvatar.setOnClickListener(loginId -> {
Context context = loginId.getContext();
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", releases.getAuthor().getLogin());
context.startActivity(intent);
});
}
}, 500);
optionsMenu.setOnClickListener(v -> {
final Context context = v.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_release_in_list, itemView.findViewById(android.R.id.content), false);
TextView deleteRelease = view.findViewById(R.id.deleteRelease);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
deleteRelease.setOnClickListener(v1 -> {
deleteRelease(context, releases.getName(), releases.getId(), repoOwner, repoName, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
} }

View File

@ -20,17 +20,6 @@ public class ReleasesDownloadsAdapter extends RecyclerView.Adapter<ReleasesDownl
private final List<Attachment> releasesDownloadsList; private final List<Attachment> releasesDownloadsList;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
static class ReleasesDownloadsViewHolder extends RecyclerView.ViewHolder {
private final TextView downloadName;
private ReleasesDownloadsViewHolder(View itemView) {
super(itemView);
downloadName = itemView.findViewById(R.id.downloadName);
}
}
ReleasesDownloadsAdapter(List<Attachment> releasesDownloadsMain, FragmentRefreshListener startDownload) { ReleasesDownloadsAdapter(List<Attachment> releasesDownloadsMain, FragmentRefreshListener startDownload) {
this.releasesDownloadsList = releasesDownloadsMain; this.releasesDownloadsList = releasesDownloadsMain;
@ -62,4 +51,16 @@ public class ReleasesDownloadsAdapter extends RecyclerView.Adapter<ReleasesDownl
return releasesDownloadsList.size(); return releasesDownloadsList.size();
} }
static class ReleasesDownloadsViewHolder extends RecyclerView.ViewHolder {
private final TextView downloadName;
private ReleasesDownloadsViewHolder(View itemView) {
super(itemView);
downloadName = itemView.findViewById(R.id.downloadName);
}
}
} }

View File

@ -17,11 +17,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -74,17 +70,35 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
return forksList.size(); return forksList.size();
} }
class ForksHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
private org.gitnex.tea4j.v2.models.Repository userRepositories; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
forksList = list;
notifyDataChanged();
}
class ForksHolder extends RecyclerView.ViewHolder {
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
ForksHolder(View itemView) { ForksHolder(View itemView) {
@ -115,13 +129,12 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
int color = generator.getColor(forksModel.getName()); int color = generator.getColor(forksModel.getName());
String firstCharacter = String.valueOf(forksModel.getFullName().charAt(0)); String firstCharacter = String.valueOf(forksModel.getFullName().charAt(0));
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28) TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28).endConfig().buildRoundRect(firstCharacter, color, 3);
.endConfig().buildRoundRect(firstCharacter, color, 3);
if(forksModel.getAvatarUrl() != null) { if(forksModel.getAvatarUrl() != null) {
if(!forksModel.getAvatarUrl().equals("")) { if(!forksModel.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(forksModel.getAvatarUrl()).placeholder(R.drawable.loader_animated) PicassoService.getInstance(context).get().load(forksModel.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); .into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -183,24 +196,7 @@ public class RepoForksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
}); });
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
forksList = list;
notifyDataChanged();
}
} }

View File

@ -7,11 +7,7 @@ import android.graphics.Typeface;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.CheckBox; import android.widget.*;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable; import com.amulyakhare.textdrawable.TextDrawable;
@ -19,11 +15,7 @@ import com.amulyakhare.textdrawable.util.ColorGenerator;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.RepoDetailActivity; import org.mian.gitnex.activities.RepoDetailActivity;
import org.mian.gitnex.clients.PicassoService; import org.mian.gitnex.clients.PicassoService;
import org.mian.gitnex.helpers.AppUtil; import org.mian.gitnex.helpers.*;
import org.mian.gitnex.helpers.ClickListener;
import org.mian.gitnex.helpers.RoundedTransformation;
import org.mian.gitnex.helpers.TimeHelper;
import org.mian.gitnex.helpers.TinyDB;
import org.mian.gitnex.helpers.contexts.RepositoryContext; import org.mian.gitnex.helpers.contexts.RepositoryContext;
import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.PrettyTime;
import java.text.DateFormat; import java.text.DateFormat;
@ -39,12 +31,46 @@ import java.util.Locale;
public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable { public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final Context context; private final Context context;
private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private final List<org.gitnex.tea4j.v2.models.Repository> reposListFull; private final List<org.gitnex.tea4j.v2.models.Repository> reposListFull;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final TinyDB tinyDb; private final TinyDB tinyDb;
public boolean isUserOrg = false; public boolean isUserOrg = false;
private List<org.gitnex.tea4j.v2.models.Repository> reposList;
private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true;
private final Filter reposFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<org.gitnex.tea4j.v2.models.Repository> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(reposListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(org.gitnex.tea4j.v2.models.Repository item : reposListFull) {
if(item.getFullName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
reposList.clear();
reposList.addAll((List) results.values);
notifyDataChanged();
}
};
public ReposListAdapter(List<org.gitnex.tea4j.v2.models.Repository> reposListMain, Context ctx) { public ReposListAdapter(List<org.gitnex.tea4j.v2.models.Repository> reposListMain, Context ctx) {
this.context = ctx; this.context = ctx;
@ -80,18 +106,53 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
return reposList.size(); return reposList.size();
} }
class ReposHolder extends RecyclerView.ViewHolder { public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
private org.gitnex.tea4j.v2.models.Repository userRepositories; @SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return reposFilter;
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
class ReposHolder extends RecyclerView.ViewHolder {
private final ImageView image; private final ImageView image;
private final TextView repoName; private final TextView repoName;
private final TextView orgName; private final TextView orgName;
private final TextView repoDescription; private final TextView repoDescription;
private CheckBox isRepoAdmin;
private final TextView repoStars; private final TextView repoStars;
private final TextView repoLastUpdated; private final TextView repoLastUpdated;
private final View spacerView; private final View spacerView;
private org.gitnex.tea4j.v2.models.Repository userRepositories;
private CheckBox isRepoAdmin;
ReposHolder(View itemView) { ReposHolder(View itemView) {
@ -137,7 +198,8 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
if(repositories.getAvatarUrl() != null) { if(repositories.getAvatarUrl() != null) {
if(!repositories.getAvatarUrl().equals("")) { if(!repositories.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(repositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(image); PicassoService.getInstance(context).get().load(repositories.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(image);
} }
else { else {
image.setImageDrawable(drawable); image.setImageDrawable(drawable);
@ -190,73 +252,7 @@ public class ReposListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHold
} }
isRepoAdmin.setChecked(repositories.getPermissions().isAdmin()); isRepoAdmin.setChecked(repositories.getPermissions().isAdmin());
} }
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
if(!isMoreDataAvailable) {
loadMoreListener.onLoadFinished();
}
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
loadMoreListener.onLoadFinished();
}
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<org.gitnex.tea4j.v2.models.Repository> list) {
reposList = list;
notifyDataChanged();
}
@Override
public Filter getFilter() {
return reposFilter;
}
private final Filter reposFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<org.gitnex.tea4j.v2.models.Repository> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() == 0) {
filteredList.addAll(reposListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(org.gitnex.tea4j.v2.models.Repository item : reposListFull) {
if(item.getFullName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
reposList.clear();
reposList.addAll((List) results.values);
notifyDataChanged();
}
};
} }

View File

@ -31,60 +31,15 @@ import retrofit2.Response;
public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder> { public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder> {
private List<Tag> tags;
private final Context context; private final Context context;
private final String repo; private final String repo;
private final String owner; private final String owner;
private final FragmentRefreshListener startDownload; private final FragmentRefreshListener startDownload;
private final FragmentReleasesBinding fragmentReleasesBinding; private final FragmentReleasesBinding fragmentReleasesBinding;
private List<Tag> tags;
private OnLoadMoreListener loadMoreListener; private OnLoadMoreListener loadMoreListener;
private boolean isLoading = false, isMoreDataAvailable = true; private boolean isLoading = false, isMoreDataAvailable = true;
protected class TagsViewHolder extends RecyclerView.ViewHolder {
private Tag tagsHolder;
private final TextView tagName;
private final TextView tagBody;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final ImageView options;
private TagsViewHolder(View itemView) {
super(itemView);
tagName = itemView.findViewById(R.id.tagName);
tagBody = itemView.findViewById(R.id.tagBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
options = itemView.findViewById(R.id.tagsOptionsMenu);
options.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams")
View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_tag_in_list, null);
TextView delete = view.findViewById(R.id.tagMenuDelete);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
delete.setOnClickListener(v1 -> {
tagDeleteDialog(context, tagsHolder.getName(), owner, repo, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
public TagsAdapter(Context ctx, List<Tag> releasesMain, String repoOwner, String repoName, FragmentRefreshListener startDownload, FragmentReleasesBinding fragmentReleasesBinding) { public TagsAdapter(Context ctx, List<Tag> releasesMain, String repoOwner, String repoName, FragmentRefreshListener startDownload, FragmentReleasesBinding fragmentReleasesBinding) {
this.context = ctx; this.context = ctx;
this.tags = releasesMain; this.tags = releasesMain;
@ -162,11 +117,6 @@ public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder
loadMoreListener.onLoadFinished(); loadMoreListener.onLoadFinished();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) { public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener; this.loadMoreListener = loadMoreListener;
} }
@ -184,13 +134,9 @@ public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder
private void tagDeleteDialog(final Context context, final String tagName, final String owner, final String repo, int position) { private void tagDeleteDialog(final Context context, final String tagName, final String owner, final String repo, int position) {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context) MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context).setTitle(String.format(context.getString(R.string.deleteGenericTitle), tagName))
.setTitle(String.format(context.getString(R.string.deleteGenericTitle), tagName)) .setMessage(R.string.deleteTagConfirmation).setCancelable(false).setNeutralButton(R.string.cancelButton, null)
.setMessage(R.string.deleteTagConfirmation) .setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient.getApiInterface(context).repoDeleteTag(owner, repo, tagName).enqueue(new Callback<>() {
.setCancelable(false)
.setNeutralButton(R.string.cancelButton, null)
.setPositiveButton(R.string.menuDeleteText, (dialog, whichButton) -> RetrofitClient
.getApiInterface(context).repoDeleteTag(owner, repo, tagName).enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) { public void onResponse(@NonNull Call<Void> call, @NonNull Response<Void> response) {
@ -218,9 +164,62 @@ public class TagsAdapter extends RecyclerView.Adapter<TagsAdapter.TagsViewHolder
Toasty.error(context, context.getString(R.string.genericError)); Toasty.error(context, context.getString(R.string.genericError));
} }
})) })).setNeutralButton(R.string.cancelButton, null);
.setNeutralButton(R.string.cancelButton, null);
materialAlertDialogBuilder.create().show(); materialAlertDialogBuilder.create().show();
} }
public interface OnLoadMoreListener {
void onLoadMore();
void onLoadFinished();
}
protected class TagsViewHolder extends RecyclerView.ViewHolder {
private final TextView tagName;
private final TextView tagBody;
private final LinearLayout downloadCopyFrame;
private final LinearLayout downloads;
private final LinearLayout releaseZipDownloadFrame;
private final LinearLayout releaseTarDownloadFrame;
private final ImageView downloadDropdownIcon;
private final ImageView options;
private Tag tagsHolder;
private TagsViewHolder(View itemView) {
super(itemView);
tagName = itemView.findViewById(R.id.tagName);
tagBody = itemView.findViewById(R.id.tagBodyContent);
downloadCopyFrame = itemView.findViewById(R.id.downloadCopyFrame);
downloads = itemView.findViewById(R.id.downloads);
releaseZipDownloadFrame = itemView.findViewById(R.id.releaseZipDownloadFrame);
releaseTarDownloadFrame = itemView.findViewById(R.id.releaseTarDownloadFrame);
downloadDropdownIcon = itemView.findViewById(R.id.downloadDropdownIcon);
options = itemView.findViewById(R.id.tagsOptionsMenu);
options.setOnClickListener(v -> {
final Context context = v.getContext();
@SuppressLint("InflateParams") View view = LayoutInflater.from(context).inflate(R.layout.bottom_sheet_tag_in_list, null);
TextView delete = view.findViewById(R.id.tagMenuDelete);
BottomSheetDialog dialog = new BottomSheetDialog(context);
dialog.setContentView(view);
dialog.show();
delete.setOnClickListener(v1 -> {
tagDeleteDialog(context, tagsHolder.getName(), owner, repo, getBindingAdapterPosition());
dialog.dismiss();
});
});
}
}
} }

View File

@ -39,11 +39,7 @@ public class TeamMembersByOrgPreviewAdapter extends RecyclerView.Adapter<TeamMem
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User userInfo = userData.get(position); User userInfo = userData.get(position);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 3), 0)).resize(120, 120)
.load(userInfo.getAvatarUrl())
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(AppUtil.getPixelsFromDensity(context, 3), 0))
.resize(120, 120)
.centerCrop().into(holder.avatar); .centerCrop().into(holder.avatar);
} }
@ -60,5 +56,7 @@ public class TeamMembersByOrgPreviewAdapter extends RecyclerView.Adapter<TeamMem
super(itemView); super(itemView);
avatar = itemView.findViewById(R.id.avatar); avatar = itemView.findViewById(R.id.avatar);
} }
} }
} }

View File

@ -49,13 +49,70 @@ public class TeamRepositoriesAdapter extends RecyclerView.Adapter<TeamRepositori
reposArr = new ArrayList<>(); reposArr = new ArrayList<>();
} }
class TeamReposViewHolder extends RecyclerView.ViewHolder { @NonNull
@Override
public TeamRepositoriesAdapter.TeamReposViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new TeamRepositoriesAdapter.TeamReposViewHolder(v);
}
private Repository repoInfo; @Override
public void onBindViewHolder(@NonNull final TeamRepositoriesAdapter.TeamReposViewHolder holder, int position) {
Repository currentItem = reposList.get(position);
holder.repoInfo = currentItem;
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
holder.name.setText(currentItem.getName());
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28).endConfig()
.buildRoundRect(String.valueOf(currentItem.getFullName().charAt(0)), ColorGenerator.Companion.getMATERIAL().getColor(currentItem.getName()), 14);
if(currentItem.getAvatarUrl() != null && !currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.repoAvatar);
}
else {
holder.repoAvatar.setImageDrawable(drawable);
}
}
@Override
public int getItemCount() {
return reposList.size();
}
private void getTeamRepos() {
if(getItemCount() > 0) {
Call<List<Repository>> call = RetrofitClient.getApiInterface(context).orgListTeamRepos((long) teamId, 1, 50);
call.enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<List<Repository>> call, @NonNull Response<List<Repository>> response) {
if(response.code() == 200) {
for(int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) {
reposArr.addAll(response.body());
}
}
}
@Override
public void onFailure(@NonNull Call<List<Repository>> call, @NonNull Throwable t) {
}
});
}
}
class TeamReposViewHolder extends RecyclerView.ViewHolder {
private final ImageView repoAvatar; private final ImageView repoAvatar;
private final TextView name; private final TextView name;
private final ImageView addRepoButtonAdd; private final ImageView addRepoButtonAdd;
private Repository repoInfo;
private TeamReposViewHolder(View itemView) { private TeamReposViewHolder(View itemView) {
@ -89,69 +146,9 @@ public class TeamRepositoriesAdapter extends RecyclerView.Adapter<TeamRepositori
addRepoButtonAdd.setOnClickListener(v -> AlertDialogs.addRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName)); addRepoButtonAdd.setOnClickListener(v -> AlertDialogs.addRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
addRepoButtonRemove.setOnClickListener(v -> addRepoButtonRemove.setOnClickListener(v -> AlertDialogs.removeRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
AlertDialogs.removeRepoDialog(context, orgName, repoInfo.getName(), Integer.parseInt(String.valueOf(teamId)), teamName));
} }
} }
@NonNull
@Override
public TeamRepositoriesAdapter.TeamReposViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_collaborators_search, parent, false);
return new TeamRepositoriesAdapter.TeamReposViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull final TeamRepositoriesAdapter.TeamReposViewHolder holder, int position) {
Repository currentItem = reposList.get(position);
holder.repoInfo = currentItem;
int imgRadius = AppUtil.getPixelsFromDensity(context, 60);
holder.name.setText(currentItem.getName());
TextDrawable drawable = TextDrawable.builder().beginConfig().useFont(Typeface.DEFAULT).fontSize(18).toUpperCase().width(28).height(28)
.endConfig().buildRoundRect(String.valueOf(currentItem.getFullName().charAt(0)), ColorGenerator.Companion.getMATERIAL().getColor(currentItem.getName()), 14);
if(currentItem.getAvatarUrl() != null && !currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.repoAvatar);
}
else {
holder.repoAvatar.setImageDrawable(drawable);
}
}
@Override
public int getItemCount() {
return reposList.size();
}
private void getTeamRepos() {
if(getItemCount() > 0) {
Call<List<Repository>> call = RetrofitClient
.getApiInterface(context)
.orgListTeamRepos((long) teamId, 1, 50);
call.enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<List<Repository>> call, @NonNull Response<List<Repository>> response) {
if(response.code() == 200) {
for(int i = 0; i < Objects.requireNonNull(response.body()).size(); i++) {
reposArr.addAll(response.body());
}
}
}
@Override
public void onFailure(@NonNull Call<List<Repository>> call, @NonNull Throwable t) {
}
});
}
}
} }

View File

@ -36,46 +36,38 @@ public class TeamsByOrgAdapter extends RecyclerView.Adapter<TeamsByOrgAdapter.Or
private final List<Team> teamListFull; private final List<Team> teamListFull;
private final OrganizationPermissions permissions; private final OrganizationPermissions permissions;
private final String orgName; private final String orgName;
private final Filter orgTeamsFilter = new Filter() {
static class OrgTeamsViewHolder extends RecyclerView.ViewHolder { @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Team> filteredList = new ArrayList<>();
private Team team; if(constraint == null || constraint.length() == 0) {
filteredList.addAll(teamListFull);
}
else {
String filterPattern = constraint.toString().toLowerCase().trim();
private OrganizationPermissions permissions; for(Team item : teamListFull) {
private final TextView teamTitle; if(item.getName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) {
private final TextView teamDescription; filteredList.add(item);
private final LinearLayout membersPreviewFrame;
private final List<User> userInfos;
private final TeamMembersByOrgPreviewAdapter adapter;
private String orgName;
private OrgTeamsViewHolder(View itemView) {
super(itemView);
teamTitle = itemView.findViewById(R.id.teamTitle);
teamDescription = itemView.findViewById(R.id.teamDescription);
membersPreviewFrame = itemView.findViewById(R.id.membersPreviewFrame);
RecyclerView membersPreview = itemView.findViewById(R.id.membersPreview);
userInfos = new ArrayList<>();
adapter = new TeamMembersByOrgPreviewAdapter(itemView.getContext(), userInfos);
membersPreview.setLayoutManager(new LinearLayoutManager(itemView.getContext(), RecyclerView.HORIZONTAL, false));
membersPreview.setAdapter(adapter);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationTeamInfoActivity.class);
intent.putExtra("team", team);
intent.putExtra("permissions", permissions);
intent.putExtra("orgName", orgName);
context.startActivity(intent);
});
} }
} }
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
teamList.clear();
teamList.addAll((List<Team>) results.values);
notifyDataSetChanged();
}
};
public TeamsByOrgAdapter(Context ctx, List<Team> teamListMain, OrganizationPermissions permissions, String orgName) { public TeamsByOrgAdapter(Context ctx, List<Team> teamListMain, OrganizationPermissions permissions, String orgName) {
this.context = ctx; this.context = ctx;
@ -106,31 +98,29 @@ public class TeamsByOrgAdapter extends RecyclerView.Adapter<TeamsByOrgAdapter.Or
holder.userInfos.clear(); holder.userInfos.clear();
holder.adapter.notifyDataSetChanged(); holder.adapter.notifyDataSetChanged();
RetrofitClient.getApiInterface(context) RetrofitClient.getApiInterface(context).orgListTeamMembers(currentItem.getId(), null, null).enqueue(new Callback<List<User>>() {
.orgListTeamMembers(currentItem.getId(), null, null)
.enqueue(new Callback<List<User>>() {
@Override @Override
public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) { public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
if(response.isSuccessful() && if(response.isSuccessful() && response.body() != null && response.body().size() > 0) {
response.body() != null &&
response.body().size() > 0) {
holder.membersPreviewFrame.setVisibility(View.VISIBLE); holder.membersPreviewFrame.setVisibility(View.VISIBLE);
holder.userInfos.addAll(response.body().stream() holder.userInfos.addAll(response.body().stream().limit(Math.min(response.body().size(), 6)).collect(Collectors.toList()));
.limit(Math.min(response.body().size(), 6))
.collect(Collectors.toList()));
holder.adapter.notifyDataSetChanged(); holder.adapter.notifyDataSetChanged();
} }
} }
@Override public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {} @Override
public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {
}
}); });
if(currentItem.getDescription() != null && !currentItem.getDescription().isEmpty()) { if(currentItem.getDescription() != null && !currentItem.getDescription().isEmpty()) {
holder.teamDescription.setVisibility(View.VISIBLE); holder.teamDescription.setVisibility(View.VISIBLE);
holder.teamDescription.setText(currentItem.getDescription()); holder.teamDescription.setText(currentItem.getDescription());
} else { }
else {
holder.teamDescription.setVisibility(View.GONE); holder.teamDescription.setVisibility(View.GONE);
holder.teamDescription.setText(""); holder.teamDescription.setText("");
} }
@ -146,35 +136,43 @@ public class TeamsByOrgAdapter extends RecyclerView.Adapter<TeamsByOrgAdapter.Or
return orgTeamsFilter; return orgTeamsFilter;
} }
private final Filter orgTeamsFilter = new Filter() { static class OrgTeamsViewHolder extends RecyclerView.ViewHolder {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Team> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) { private final TextView teamTitle;
filteredList.addAll(teamListFull); private final TextView teamDescription;
} else { private final LinearLayout membersPreviewFrame;
String filterPattern = constraint.toString().toLowerCase().trim(); private final List<User> userInfos;
private final TeamMembersByOrgPreviewAdapter adapter;
private Team team;
private OrganizationPermissions permissions;
private String orgName;
for (Team item : teamListFull) { private OrgTeamsViewHolder(View itemView) {
if (item.getName().toLowerCase().contains(filterPattern) || item.getDescription().toLowerCase().contains(filterPattern)) { super(itemView);
filteredList.add(item);
} teamTitle = itemView.findViewById(R.id.teamTitle);
} teamDescription = itemView.findViewById(R.id.teamDescription);
membersPreviewFrame = itemView.findViewById(R.id.membersPreviewFrame);
RecyclerView membersPreview = itemView.findViewById(R.id.membersPreview);
userInfos = new ArrayList<>();
adapter = new TeamMembersByOrgPreviewAdapter(itemView.getContext(), userInfos);
membersPreview.setLayoutManager(new LinearLayoutManager(itemView.getContext(), RecyclerView.HORIZONTAL, false));
membersPreview.setAdapter(adapter);
itemView.setOnClickListener(v -> {
Context context = v.getContext();
Intent intent = new Intent(context, OrganizationTeamInfoActivity.class);
intent.putExtra("team", team);
intent.putExtra("permissions", permissions);
intent.putExtra("orgName", orgName);
context.startActivity(intent);
});
} }
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
} }
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
teamList.clear();
teamList.addAll((List<Team>) results.values);
notifyDataSetChanged();
}
};
} }

View File

@ -42,98 +42,6 @@ public class UserAccountsAdapter extends RecyclerView.Adapter<UserAccountsAdapte
private final Context context; private final Context context;
private final Dialog dialog; private final Dialog dialog;
class UserAccountsViewHolder extends RecyclerView.ViewHolder {
private int accountId;
private String accountName;
private final TextView accountUrl;
private final TextView userId;
private final ImageView activeAccount;
private final ImageView deleteAccount;
private final ImageView repoAvatar;
private UserAccountsViewHolder(View itemView) {
super(itemView);
accountUrl = itemView.findViewById(R.id.accountUrl);
userId = itemView.findViewById(R.id.userId);
activeAccount = itemView.findViewById(R.id.activeAccount);
deleteAccount = itemView.findViewById(R.id.deleteAccount);
repoAvatar = itemView.findViewById(R.id.repoAvatar);
deleteAccount.setOnClickListener(itemDelete -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context)
.setTitle(context.getResources().getString(R.string.removeAccountPopupTitle))
.setMessage(context.getResources().getString(R.string.removeAccountPopupMessage))
.setNeutralButton(context.getResources().getString(R.string.cancelButton), null)
.setPositiveButton(context.getResources().getString(R.string.removeButton), (dialog, which) -> {
updateLayoutByPosition(getBindingAdapterPosition());
UserAccountsApi userAccountsApi = BaseApi.getInstance(context, UserAccountsApi.class);
assert userAccountsApi != null;
userAccountsApi.deleteAccount(Integer.parseInt(String.valueOf(accountId)));
});
materialAlertDialogBuilder.create().show();
});
itemView.setOnClickListener(switchAccount -> {
UserAccountsApi userAccountsApi = BaseApi.getInstance(context, UserAccountsApi.class);
assert userAccountsApi != null;
UserAccount userAccount = userAccountsApi.getAccountByName(accountName);
if(!userAccount.isLoggedIn()) {
UrlBuilder url = UrlBuilder.fromString(userAccount.getInstanceUrl())
.withPath("/");
String host;
if(url.scheme.equals("http")) {
if(url.port == 80 || url.port == 0) {
host = url.hostName;
} else {
host = url.hostName + ":" + url.port;
}
} else {
if(url.port == 443 || url.port == 0) {
host = url.hostName;
} else {
host = url.hostName + ":" + url.port;
}
}
Toasty.warning(context, context.getString(R.string.logInAgain));
dialog.dismiss();
Intent i = new Intent(context, AddNewAccountActivity.class);
i.putExtra("instanceUrl", host);
i.putExtra("scheme", url.scheme);
i.putExtra("token", userAccount.getToken());
context.startActivity(i);
return;
}
if(AppUtil.switchToAccount(context, userAccount)) {
String url = UrlBuilder.fromString(userAccount.getInstanceUrl())
.withPath("/")
.toString();
Toasty.success(context, context.getResources().getString(R.string.switchAccountSuccess, userAccount.getUserName(), url));
getNotificationsCount();
((Activity) context).recreate();
dialog.dismiss();
}
});
}
}
public UserAccountsAdapter(Context ctx, Dialog dialog) { public UserAccountsAdapter(Context ctx, Dialog dialog) {
this.dialog = dialog; this.dialog = dialog;
this.context = ctx; this.context = ctx;
@ -190,9 +98,7 @@ public class UserAccountsAdapter extends RecyclerView.Adapter<UserAccountsAdapte
UserAccount currentItem = userAccountsList.get(position); UserAccount currentItem = userAccountsList.get(position);
TinyDB tinyDB = TinyDB.getInstance(context); TinyDB tinyDB = TinyDB.getInstance(context);
String url = UrlBuilder.fromString(currentItem.getInstanceUrl()) String url = UrlBuilder.fromString(currentItem.getInstanceUrl()).withPath("/").toString();
.withPath("/")
.toString();
holder.accountId = currentItem.getAccountId(); holder.accountId = currentItem.getAccountId();
holder.accountName = currentItem.getAccountName(); holder.accountName = currentItem.getAccountName();
@ -200,18 +106,14 @@ public class UserAccountsAdapter extends RecyclerView.Adapter<UserAccountsAdapte
holder.userId.setText(currentItem.getUserName()); holder.userId.setText(currentItem.getUserName());
if(currentItem.isLoggedIn()) { if(currentItem.isLoggedIn()) {
holder.accountUrl.setText(url); holder.accountUrl.setText(url);
} else { }
else {
holder.accountUrl.setText(context.getString(R.string.notLoggedIn, url)); holder.accountUrl.setText(context.getString(R.string.notLoggedIn, url));
} }
int imgRadius = AppUtil.getPixelsFromDensity(context, 3); int imgRadius = AppUtil.getPixelsFromDensity(context, 3);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(url + "assets/img/favicon.png").placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.load(url + "assets/img/favicon.png")
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(imgRadius, 0))
.resize(120, 120)
.centerCrop()
.into(holder.repoAvatar); .into(holder.repoAvatar);
if(tinyDB.getInt("currentActiveAccountId") == currentItem.getAccountId()) { if(tinyDB.getInt("currentActiveAccountId") == currentItem.getAccountId()) {
@ -227,4 +129,93 @@ public class UserAccountsAdapter extends RecyclerView.Adapter<UserAccountsAdapte
return userAccountsList.size(); return userAccountsList.size();
} }
class UserAccountsViewHolder extends RecyclerView.ViewHolder {
private final TextView accountUrl;
private final TextView userId;
private final ImageView activeAccount;
private final ImageView deleteAccount;
private final ImageView repoAvatar;
private int accountId;
private String accountName;
private UserAccountsViewHolder(View itemView) {
super(itemView);
accountUrl = itemView.findViewById(R.id.accountUrl);
userId = itemView.findViewById(R.id.userId);
activeAccount = itemView.findViewById(R.id.activeAccount);
deleteAccount = itemView.findViewById(R.id.deleteAccount);
repoAvatar = itemView.findViewById(R.id.repoAvatar);
deleteAccount.setOnClickListener(itemDelete -> {
MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context).setTitle(context.getResources().getString(R.string.removeAccountPopupTitle))
.setMessage(context.getResources().getString(R.string.removeAccountPopupMessage)).setNeutralButton(context.getResources().getString(R.string.cancelButton), null)
.setPositiveButton(context.getResources().getString(R.string.removeButton), (dialog, which) -> {
updateLayoutByPosition(getBindingAdapterPosition());
UserAccountsApi userAccountsApi = BaseApi.getInstance(context, UserAccountsApi.class);
assert userAccountsApi != null;
userAccountsApi.deleteAccount(Integer.parseInt(String.valueOf(accountId)));
});
materialAlertDialogBuilder.create().show();
});
itemView.setOnClickListener(switchAccount -> {
UserAccountsApi userAccountsApi = BaseApi.getInstance(context, UserAccountsApi.class);
assert userAccountsApi != null;
UserAccount userAccount = userAccountsApi.getAccountByName(accountName);
if(!userAccount.isLoggedIn()) {
UrlBuilder url = UrlBuilder.fromString(userAccount.getInstanceUrl()).withPath("/");
String host;
if(url.scheme.equals("http")) {
if(url.port == 80 || url.port == 0) {
host = url.hostName;
}
else {
host = url.hostName + ":" + url.port;
}
}
else {
if(url.port == 443 || url.port == 0) {
host = url.hostName;
}
else {
host = url.hostName + ":" + url.port;
}
}
Toasty.warning(context, context.getString(R.string.logInAgain));
dialog.dismiss();
Intent i = new Intent(context, AddNewAccountActivity.class);
i.putExtra("instanceUrl", host);
i.putExtra("scheme", url.scheme);
i.putExtra("token", userAccount.getToken());
context.startActivity(i);
return;
}
if(AppUtil.switchToAccount(context, userAccount)) {
String url = UrlBuilder.fromString(userAccount.getInstanceUrl()).withPath("/").toString();
Toasty.success(context, context.getResources().getString(R.string.switchAccountSuccess, userAccount.getUserName(), url));
getNotificationsCount();
((Activity) context).recreate();
dialog.dismiss();
}
});
}
}
} }

View File

@ -41,23 +41,6 @@ public class UserAccountsNavAdapter extends RecyclerView.Adapter<UserAccountsNav
this.drawer = drawerLayout; this.drawer = drawerLayout;
} }
class UserAccountsViewHolder extends RecyclerView.ViewHolder {
private final ImageView userAccountAvatar;
private UserAccountsViewHolder(View itemView) {
super(itemView);
userAccountAvatar = itemView.findViewById(R.id.userAccountAvatar);
itemView.setOnClickListener(item -> {
customDialogUserAccountsList();
drawer.closeDrawers();
});
}
}
@NonNull @NonNull
@Override @Override
public UserAccountsNavAdapter.UserAccountsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public UserAccountsNavAdapter.UserAccountsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -72,18 +55,11 @@ public class UserAccountsNavAdapter extends RecyclerView.Adapter<UserAccountsNav
UserAccount currentItem = userAccountsList.get(position); UserAccount currentItem = userAccountsList.get(position);
String url = UrlBuilder.fromString(currentItem.getInstanceUrl()) String url = UrlBuilder.fromString(currentItem.getInstanceUrl()).withPath("/").toString();
.withPath("/")
.toString();
int imageSize = AppUtil.getPixelsFromDensity(context, 35); int imageSize = AppUtil.getPixelsFromDensity(context, 35);
PicassoService.getInstance(context).get() PicassoService.getInstance(context).get().load(url + "assets/img/favicon.png").placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(8, 0)).resize(imageSize, imageSize).centerCrop()
.load(url + "assets/img/favicon.png")
.placeholder(R.drawable.loader_animated)
.transform(new RoundedTransformation(8, 0))
.resize(imageSize, imageSize)
.centerCrop()
.into(holder.userAccountAvatar); .into(holder.userAccountAvatar);
} }
@ -117,4 +93,22 @@ public class UserAccountsNavAdapter extends RecyclerView.Adapter<UserAccountsNav
dialog.show(); dialog.show();
} }
class UserAccountsViewHolder extends RecyclerView.ViewHolder {
private final ImageView userAccountAvatar;
private UserAccountsViewHolder(View itemView) {
super(itemView);
userAccountAvatar = itemView.findViewById(R.id.userAccountAvatar);
itemView.setOnClickListener(item -> {
customDialogUserAccountsList();
drawer.closeDrawers();
});
}
}
} }

View File

@ -7,11 +7,7 @@ import android.text.Html;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.BaseAdapter; import android.widget.*;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import org.gitnex.tea4j.v2.models.User; import org.gitnex.tea4j.v2.models.User;
import org.mian.gitnex.R; import org.mian.gitnex.R;
import org.mian.gitnex.activities.ProfileActivity; import org.mian.gitnex.activities.ProfileActivity;
@ -30,31 +26,40 @@ public class UserGridAdapter extends BaseAdapter implements Filterable {
private final List<User> membersList; private final List<User> membersList;
private final Context context; private final Context context;
private final List<User> membersListFull; private final List<User> membersListFull;
private final Filter membersFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
private class ViewHolder { if(constraint == null || constraint.length() == 0) {
private String userLoginId; filteredList.addAll(membersListFull);
}
else {
private final ImageView memberAvatar; String filterPattern = constraint.toString().toLowerCase().trim();
private final TextView memberName;
ViewHolder(View v) { for(User item : membersListFull) {
if(item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) {
memberAvatar = v.findViewById(R.id.userAvatarImageView); filteredList.add(item);
memberName = v.findViewById(R.id.userNameTv);
v.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userLoginId);
context.startActivity(intent);
});
v.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
} }
} }
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
membersList.clear();
membersList.addAll((List) results.values);
notifyDataSetChanged();
}
};
public UserGridAdapter(Context ctx, List<User> membersListMain) { public UserGridAdapter(Context ctx, List<User> membersListMain) {
@ -104,7 +109,8 @@ public class UserGridAdapter extends BaseAdapter implements Filterable {
User currentItem = membersList.get(position); User currentItem = membersList.get(position);
int imgRadius = AppUtil.getPixelsFromDensity(context, 0); int imgRadius = AppUtil.getPixelsFromDensity(context, 0);
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(viewHolder.memberAvatar); PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(viewHolder.memberAvatar);
viewHolder.userLoginId = currentItem.getLogin(); viewHolder.userLoginId = currentItem.getLogin();
@ -123,39 +129,29 @@ public class UserGridAdapter extends BaseAdapter implements Filterable {
return membersFilter; return membersFilter;
} }
private final Filter membersFilter = new Filter() { private class ViewHolder {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<User> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) { private final ImageView memberAvatar;
private final TextView memberName;
private String userLoginId;
filteredList.addAll(membersListFull); ViewHolder(View v) {
}
else {
String filterPattern = constraint.toString().toLowerCase().trim(); memberAvatar = v.findViewById(R.id.userAvatarImageView);
memberName = v.findViewById(R.id.userNameTv);
for (User item : membersListFull) { v.setOnClickListener(loginId -> {
if (item.getFullName().toLowerCase().contains(filterPattern) || item.getLogin().toLowerCase().contains(filterPattern)) { Intent intent = new Intent(context, ProfileActivity.class);
filteredList.add(item); intent.putExtra("username", userLoginId);
} context.startActivity(intent);
} });
v.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userLoginId, context.getString(R.string.copyLoginIdToClipBoard, userLoginId));
return true;
});
} }
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
} }
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
membersList.clear();
membersList.addAll((List) results.values);
notifyDataSetChanged();
}
};
} }

View File

@ -44,47 +44,6 @@ public class UserSearchForTeamMemberAdapter extends RecyclerView.Adapter<UserSea
this.orgName = orgName; this.orgName = orgName;
} }
class UserSearchViewHolder extends RecyclerView.ViewHolder {
private User userInfo;
private final ImageView userAvatar;
private final TextView userFullName;
private final TextView userName;
private final ImageView addMemberButtonAdd;
private final ImageView addMemberButtonRemove;
private UserSearchViewHolder(View itemView) {
super(itemView);
userAvatar = itemView.findViewById(R.id.userAvatar);
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addMemberButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addMemberButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
addMemberButtonAdd.setOnClickListener(v -> AlertDialogs.addMemberDialog(context, userInfo.getLogin(), Integer.parseInt(String.valueOf(teamId))));
addMemberButtonRemove.setOnClickListener(v -> AlertDialogs.removeMemberDialog(context, userInfo.getLogin(), Integer.parseInt(String.valueOf(teamId))));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(userInfo.getLogin())) {
userAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userInfo.getLogin());
context.startActivity(intent);
});
userAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin()));
return true;
});
}
}, 500);
}
}
@NonNull @NonNull
@Override @Override
public UserSearchForTeamMemberAdapter.UserSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public UserSearchForTeamMemberAdapter.UserSearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
@ -111,16 +70,15 @@ public class UserSearchForTeamMemberAdapter extends RecyclerView.Adapter<UserSea
holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin())); holder.userName.setText(context.getResources().getString(R.string.usernameWithAt, currentItem.getLogin()));
if(!currentItem.getAvatarUrl().equals("")) { if(!currentItem.getAvatarUrl().equals("")) {
PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(holder.userAvatar); PicassoService.getInstance(context).get().load(currentItem.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
.into(holder.userAvatar);
} }
if(getItemCount() > 0) { if(getItemCount() > 0) {
final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName(); final String loginUid = ((BaseActivity) context).getAccount().getAccount().getUserName();
Call<User> call = RetrofitClient Call<User> call = RetrofitClient.getApiInterface(context).orgListTeamMember((long) teamId, currentItem.getLogin());
.getApiInterface(context)
.orgListTeamMember((long) teamId, currentItem.getLogin());
call.enqueue(new Callback<>() { call.enqueue(new Callback<>() {
@ -171,4 +129,44 @@ public class UserSearchForTeamMemberAdapter extends RecyclerView.Adapter<UserSea
return usersSearchList.size(); return usersSearchList.size();
} }
class UserSearchViewHolder extends RecyclerView.ViewHolder {
private final ImageView userAvatar;
private final TextView userFullName;
private final TextView userName;
private final ImageView addMemberButtonAdd;
private final ImageView addMemberButtonRemove;
private User userInfo;
private UserSearchViewHolder(View itemView) {
super(itemView);
userAvatar = itemView.findViewById(R.id.userAvatar);
userFullName = itemView.findViewById(R.id.userFullName);
userName = itemView.findViewById(R.id.userName);
addMemberButtonAdd = itemView.findViewById(R.id.addCollaboratorButtonAdd);
addMemberButtonRemove = itemView.findViewById(R.id.addCollaboratorButtonRemove);
addMemberButtonAdd.setOnClickListener(v -> AlertDialogs.addMemberDialog(context, userInfo.getLogin(), Integer.parseInt(String.valueOf(teamId))));
addMemberButtonRemove.setOnClickListener(v -> AlertDialogs.removeMemberDialog(context, userInfo.getLogin(), Integer.parseInt(String.valueOf(teamId))));
new Handler().postDelayed(() -> {
if(!AppUtil.checkGhostUsers(userInfo.getLogin())) {
userAvatar.setOnClickListener(loginId -> {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra("username", userInfo.getLogin());
context.startActivity(intent);
});
userAvatar.setOnLongClickListener(loginId -> {
AppUtil.copyToClipboard(context, userInfo.getLogin(), context.getString(R.string.copyLoginIdToClipBoard, userInfo.getLogin()));
return true;
});
}
}, 500);
}
}
} }

View File

@ -62,11 +62,31 @@ public class UsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
return followersList.size(); return followersList.size();
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
followersList = list;
notifyDataChanged();
}
class UsersHolder extends RecyclerView.ViewHolder { class UsersHolder extends RecyclerView.ViewHolder {
private User userInfo;
private final ImageView userAvatar; private final ImageView userAvatar;
private final TextView userFullName; private final TextView userFullName;
private final TextView userName; private final TextView userName;
private User userInfo;
UsersHolder(View itemView) { UsersHolder(View itemView) {
super(itemView); super(itemView);
@ -106,28 +126,12 @@ public class UsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
userName.setVisibility(View.GONE); userName.setVisibility(View.GONE);
} }
PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop().into(userAvatar); PicassoService.getInstance(context).get().load(userInfo.getAvatarUrl()).placeholder(R.drawable.loader_animated).transform(new RoundedTransformation(imgRadius, 0)).resize(120, 120).centerCrop()
} .into(userAvatar);
} }
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
} }
@SuppressLint("NotifyDataSetChanged")
public void notifyDataChanged() {
notifyDataSetChanged();
isLoading = false;
}
public void setLoadMoreListener(Runnable loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
public void updateList(List<User> list) {
followersList = list;
notifyDataChanged();
}
} }

Some files were not shown because too many files have changed in this diff Show More