diff --git a/Chan/src/org/floens/chan/chan/ChanUrls.java b/Chan/src/org/floens/chan/chan/ChanUrls.java index 93f6481f..8cbc63b3 100644 --- a/Chan/src/org/floens/chan/chan/ChanUrls.java +++ b/Chan/src/org/floens/chan/chan/ChanUrls.java @@ -6,23 +6,23 @@ public class ChanUrls { public static String getCatalogUrl(String board) { return "https://a.4cdn.org/" + board + "/catalog.json"; } - + public static String getPageUrl(String board, int pageNumber) { return "https://a.4cdn.org/" + board + "/" + pageNumber + ".json"; } - + public static String getThreadUrl(String board, int no) { return "https://a.4cdn.org/" + board + "/res/" + no + ".json"; } - + public static String getCaptchaChallengeUrl() { return "https://www.google.com/recaptcha/api/challenge?k=6Ldp2bsSAAAAAAJ5uyx_lx34lJeEpTLVkP5k04qc"; } - + public static String getCaptchaImageUrl(String challenge) { return "https://www.google.com/recaptcha/api/image?c=" + challenge; } - + public static String getImageUrl(String board, String code, String extension) { return "https://i.4cdn.org/" + board + "/src/" + code + "." + extension; } @@ -41,12 +41,12 @@ public class ChanUrls { public static String getPostUrl(String board) { return "https://sys.4chan.org/" + board + "/post"; -// return "http://192.168.6.214/Testing/PostEchoer/post.php"; + // return "http://192.168.6.214/Testing/PostEchoer/post.php"; } - + public static String getDeleteUrl(String board) { return "https://sys.4chan.org/" + board + "/imgboard.php"; -// return "http://192.168.6.214/Testing/PostEchoer/post.php"; + // return "http://192.168.6.214/Testing/PostEchoer/post.php"; } public static String getBoardUrlDesktop(String board) { @@ -61,8 +61,3 @@ public class ChanUrls { return "https://boards.4chan.org/" + board + "/catalog"; } } - - - - - diff --git a/Chan/src/org/floens/chan/core/ChanPreferences.java b/Chan/src/org/floens/chan/core/ChanPreferences.java index a7f17f6d..d292e577 100644 --- a/Chan/src/org/floens/chan/core/ChanPreferences.java +++ b/Chan/src/org/floens/chan/core/ChanPreferences.java @@ -33,9 +33,9 @@ public class ChanPreferences { } /** - * This also calls updateRunningState on the PinnedService to - * start/stop the service as needed. - * + * This also calls updateRunningState on the PinnedService to start/stop the + * service as needed. + * * @param enabled */ public static void setWatchEnabled(boolean enabled) { @@ -54,13 +54,8 @@ public class ChanPreferences { String number = ChanApplication.getPreferences().getString("preference_watch_background_timeout", "0"); return Integer.parseInt(number) * 1000L; } - + public static boolean getVideoAutoPlay() { return ChanApplication.getPreferences().getBoolean("preference_autoplay", false); } } - - - - - diff --git a/Chan/src/org/floens/chan/core/loader/EndOfLineException.java b/Chan/src/org/floens/chan/core/loader/EndOfLineException.java index f95a5b52..c3a813c9 100644 --- a/Chan/src/org/floens/chan/core/loader/EndOfLineException.java +++ b/Chan/src/org/floens/chan/core/loader/EndOfLineException.java @@ -12,7 +12,7 @@ public class EndOfLineException extends VolleyError { public EndOfLineException() { super(); } - + @Override public String getMessage() { return "End of the line"; diff --git a/Chan/src/org/floens/chan/core/loader/Loader.java b/Chan/src/org/floens/chan/core/loader/Loader.java index db3ea577..2970f9ac 100644 --- a/Chan/src/org/floens/chan/core/loader/Loader.java +++ b/Chan/src/org/floens/chan/core/loader/Loader.java @@ -43,7 +43,7 @@ public class Loader { /** * Add a LoaderListener - * + * * @param l * the listener to add */ @@ -53,7 +53,7 @@ public class Loader { /** * Remove a LoaderListener - * + * * @param l * the listener to remove * @return true if there are no more listeners, false otherwise @@ -85,9 +85,9 @@ public class Loader { } /** - * Request more data if the time left is below 0 - * If auto load more is disabled, this needs to be called manually. - * Otherwise this is called automatically when the timer hits 0. + * Request more data if the time left is below 0 If auto load more is + * disabled, this needs to be called manually. Otherwise this is called + * automatically when the timer hits 0. */ public void loadMoreIfTime() { if (getTimeUntilLoadMore() < 0L) { @@ -165,6 +165,7 @@ public class Loader { /** * Get the time in milliseconds until another loadMore is recommended + * * @return */ public long getTimeUntilLoadMore() { @@ -175,7 +176,7 @@ public class Loader { return lastLoadTime + waitTime - System.currentTimeMillis(); } } - + public List getCachedPosts() { return cachedPosts; } @@ -291,6 +292,7 @@ public class Loader { public static interface LoaderListener { public void onData(List result, boolean append); + public void onError(VolleyError error); } } diff --git a/Chan/src/org/floens/chan/core/loader/LoaderPool.java b/Chan/src/org/floens/chan/core/loader/LoaderPool.java index a8e9d3fa..8f8deaaa 100644 --- a/Chan/src/org/floens/chan/core/loader/LoaderPool.java +++ b/Chan/src/org/floens/chan/core/loader/LoaderPool.java @@ -6,7 +6,7 @@ import java.util.Map; import org.floens.chan.core.model.Loadable; public class LoaderPool { -// private static final String TAG = "LoaderPool"; + // private static final String TAG = "LoaderPool"; private static LoaderPool instance; diff --git a/Chan/src/org/floens/chan/core/manager/BoardManager.java b/Chan/src/org/floens/chan/core/manager/BoardManager.java index 17892b06..e682d201 100644 --- a/Chan/src/org/floens/chan/core/manager/BoardManager.java +++ b/Chan/src/org/floens/chan/core/manager/BoardManager.java @@ -37,6 +37,7 @@ public class BoardManager { /** * Avoid having 0 boards, which causes graphical problems + * * @param list */ private ArrayList getDefaultBoards() { @@ -125,6 +126,7 @@ public class BoardManager { /** * Try to add value to the supplied list. + * * @param list * @param value */ @@ -174,7 +176,8 @@ public class BoardManager { private ArrayList getBoardListFromDatabase(String key) { String total = ChanApplication.getPreferences().getString(key, null); - if (total == null) return null; + if (total == null) + return null; ArrayList list = new ArrayList(); @@ -184,7 +187,8 @@ public class BoardManager { String line = scanner.nextLine(); String[] splitted = line.split("\\|"); - if (splitted.length < 2) continue; + if (splitted.length < 2) + continue; Board board = new Board(); board.key = splitted[0]; @@ -207,24 +211,20 @@ public class BoardManager { allBoards = temp; } - ChanApplication.getVolleyRequestQueue().add(new BoardsRequest(ChanUrls.getBoardsUrl(), new Response.Listener>() { - @Override - public void onResponse(ArrayList data) { - storeBoardListInDatabase("allBoards", data); - allBoards = data; - - Logger.i(TAG, "Got boards from server"); - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - Logger.e(TAG, "Failed to get boards from server"); - } - })); + ChanApplication.getVolleyRequestQueue().add( + new BoardsRequest(ChanUrls.getBoardsUrl(), new Response.Listener>() { + @Override + public void onResponse(ArrayList data) { + storeBoardListInDatabase("allBoards", data); + allBoards = data; + + Logger.i(TAG, "Got boards from server"); + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Logger.e(TAG, "Failed to get boards from server"); + } + })); } } - - - - - diff --git a/Chan/src/org/floens/chan/core/manager/PinnedManager.java b/Chan/src/org/floens/chan/core/manager/PinnedManager.java index 4cc64a8f..0521f050 100644 --- a/Chan/src/org/floens/chan/core/manager/PinnedManager.java +++ b/Chan/src/org/floens/chan/core/manager/PinnedManager.java @@ -28,7 +28,7 @@ public class PinnedManager { /** * Look for a pin that has an loadable that is equal to the supplied * loadable. - * + * * @param other * @return The pin whose loadable is equal to the supplied loadable, or null * if no pin was found. @@ -60,7 +60,7 @@ public class PinnedManager { /** * Add a pin - * + * * @param pin * @return true if it was added, false if it wasn't (duplicated) */ @@ -82,7 +82,7 @@ public class PinnedManager { /** * Remove a pin - * + * * @param pin */ public void remove(Pin pin) { @@ -95,7 +95,7 @@ public class PinnedManager { /** * Update the pin in the database - * + * * @param pin */ public void update(Pin pin) { diff --git a/Chan/src/org/floens/chan/core/manager/ReplyManager.java b/Chan/src/org/floens/chan/core/manager/ReplyManager.java index 114876bf..b0956533 100644 --- a/Chan/src/org/floens/chan/core/manager/ReplyManager.java +++ b/Chan/src/org/floens/chan/core/manager/ReplyManager.java @@ -59,7 +59,9 @@ public class ReplyManager { /** * Set an reply draft. - * @param value the draft to save. + * + * @param value + * the draft to save. */ public void setReplyDraft(Reply value) { draft = value; @@ -67,6 +69,7 @@ public class ReplyManager { /** * Gets the saved reply draft. + * * @return the saved draft or an empty draft. */ public Reply getReplyDraft() { @@ -75,7 +78,9 @@ public class ReplyManager { /** * Add an quote to the comment field. Looks like >>123456789\n - * @param no the raw no to quote to. + * + * @param no + * the raw no to quote to. */ public void quote(int no) { draft.comment = draft.comment + ">>" + no + "\n"; @@ -83,7 +88,9 @@ public class ReplyManager { /** * Pick an file. Starts up the ImagePickActivity. - * @param listener FileListener to listen on. + * + * @param listener + * FileListener to listen on. */ public void pickFile(FileListener listener) { fileListener = listener; @@ -103,7 +110,8 @@ public class ReplyManager { } /** - * Called from ImagePickActivity. Sends the file to the listening fileListener, and deletes the fileListener. + * Called from ImagePickActivity. Sends the file to the listening + * fileListener, and deletes the fileListener. */ public void _onPickedFile(File file) { if (fileListener != null) { @@ -121,7 +129,9 @@ public class ReplyManager { /** * Get the CAPTCHA challenge hash from an JSON response. - * @param total The total response from the server + * + * @param total + * The total response from the server * @return The pattern, or null when none was found. */ public static String getChallenge(String total) { @@ -137,8 +147,12 @@ public class ReplyManager { /** * Send an reply off to the server. - * @param reply The reply object with all data needed, like captcha and the file. - * @param listener The listener, after server response. + * + * @param reply + * The reply object with all data needed, like captcha and the + * file. + * @param listener + * The listener, after server response. */ public void sendDelete(final SavedReply reply, boolean onlyImageDelete, final DeleteListener listener) { Logger.i(TAG, "Sending delete request: " + reply.board + ", " + reply.no); @@ -196,8 +210,12 @@ public class ReplyManager { /** * Send an reply off to the server. - * @param reply The reply object with all data needed, like captcha and the file. - * @param listener The listener, after server response. + * + * @param reply + * The reply object with all data needed, like captcha and the + * file. + * @param listener + * The listener, after server response. */ public void sendReply(final Reply reply, final ReplyListener listener) { Logger.i(TAG, "Sending reply request: " + reply.board + ", " + reply.resto); @@ -248,8 +266,8 @@ public class ReplyManager { if (responseString.contains("No file selected")) { e.isUserError = true; e.isFileError = true; - } else if (responseString.contains("You forgot to solve the CAPTCHA") || - responseString.contains("You seem to have mistyped the CAPTCHA")) { + } else if (responseString.contains("You forgot to solve the CAPTCHA") + || responseString.contains("You seem to have mistyped the CAPTCHA")) { e.isUserError = true; e.isCaptchaError = true; } else if (responseString.toLowerCase(Locale.ENGLISH).contains("post successful")) { @@ -282,11 +300,12 @@ public class ReplyManager { } /** - * Async task to send an reply to the server. - * Uses HttpClient. Since Android 4.4 there is an updated version of HttpClient, 4.2, given with Android. - * However, that version causes problems with file uploading. Version 4.3 of HttpClient has been given with a library, - * that has another namespace: ch.boye.httpclientandroidlib - * This lib also has some fixes/improvements of HttpClient for Android. + * Async task to send an reply to the server. Uses HttpClient. Since Android + * 4.4 there is an updated version of HttpClient, 4.2, given with Android. + * However, that version causes problems with file uploading. Version 4.3 of + * HttpClient has been given with a library, that has another namespace: + * ch.boye.httpclientandroidlib This lib also has some fixes/improvements of + * HttpClient for Android. */ private void sendHttpPost(final HttpPost post, final HttpPostSendListener listener) { new Thread(new Runnable() { @@ -328,9 +347,12 @@ public class ReplyManager { public static abstract class FileListener { /** * When a file is picked. - * @param the picked file + * + * @param the + * picked file */ public abstract void onFile(File file); + /** * When the file has started loading. */ @@ -382,14 +404,9 @@ public class ReplyManager { public boolean isSuccessful = false; /** - * Raw html from the response. Used to set html in an WebView to the client, when the error was not - * recognized by Chan. + * Raw html from the response. Used to set html in an WebView to the + * client, when the error was not recognized by Chan. */ public String responseData = ""; } } - - - - - diff --git a/Chan/src/org/floens/chan/core/manager/ThreadManager.java b/Chan/src/org/floens/chan/core/manager/ThreadManager.java index 34639809..9ece1ef2 100644 --- a/Chan/src/org/floens/chan/core/manager/ThreadManager.java +++ b/Chan/src/org/floens/chan/core/manager/ThreadManager.java @@ -53,7 +53,7 @@ public class ThreadManager implements Loader.LoaderListener { private int highlightedPost = -1; private int lastSeenPost = -1; private int lastPost = -1; - + private Loader loader; public ThreadManager(Activity activity, final ThreadManagerListener listener) { @@ -111,7 +111,7 @@ public class ThreadManager implements Loader.LoaderListener { if (pin != null) { ChanApplication.getPinnedManager().onPinViewed(pin); } - + updateLastSeen(); } } @@ -150,7 +150,7 @@ public class ThreadManager implements Loader.LoaderListener { if (!shouldWatch()) { loader.setAutoLoadMore(false); } - + if (result.size() > 0) { lastPost = result.get(result.size() - 1).no; } @@ -277,7 +277,8 @@ public class ThreadManager implements Loader.LoaderListener { String text = ""; if (post.hasImage) { - text += "File: " + post.filename + "." + post.ext + " \nSize: " + post.imageWidth + "x" + post.imageHeight + "\n\n"; + text += "File: " + post.filename + "." + post.ext + " \nSize: " + post.imageWidth + "x" + post.imageHeight + + "\n\n"; } text += "Time: " + post.date; @@ -536,7 +537,7 @@ public class ThreadManager implements Loader.LoaderListener { } }); } - + private void updateLastSeen() { Pin pin = ChanApplication.getPinnedManager().findPinByLoadable(loader.getLoadable()); if (pin != null) { diff --git a/Chan/src/org/floens/chan/core/model/Board.java b/Chan/src/org/floens/chan/core/model/Board.java index dc4f5a91..73f45ca4 100644 --- a/Chan/src/org/floens/chan/core/model/Board.java +++ b/Chan/src/org/floens/chan/core/model/Board.java @@ -1,9 +1,8 @@ package org.floens.chan.core.model; /** - * Board key and value. - * key is full name e.g. Literature. - * value is board key e.g. lit. + * Board key and value. key is full name e.g. Literature. value is board key + * e.g. lit. */ public class Board { /** @@ -14,15 +13,16 @@ public class Board { * Name of the url, e.g. lit */ public String value; - + public boolean workSafe = false; - + public boolean finish() { - if (key == null || value == null) return false; - + if (key == null || value == null) + return false; + return true; } - + @Override public String toString() { return key; diff --git a/Chan/src/org/floens/chan/core/model/Loadable.java b/Chan/src/org/floens/chan/core/model/Loadable.java index 37510a07..806f927c 100644 --- a/Chan/src/org/floens/chan/core/model/Loadable.java +++ b/Chan/src/org/floens/chan/core/model/Loadable.java @@ -13,40 +13,40 @@ import com.j256.ormlite.table.DatabaseTable; public class Loadable { @DatabaseField(generatedId = true) private int id; - + @DatabaseField public int mode = Mode.INVALID; - + @DatabaseField public String board = ""; - + @DatabaseField public int no = -1; - + @DatabaseField public String title = ""; - + @DatabaseField public int listViewIndex; - + @DatabaseField public int listViewTop; - + /** - * When simple mode is enabled, CPU intensive methods won't get called. - * This is used for the thread watcher. + * When simple mode is enabled, CPU intensive methods won't get called. This + * is used for the thread watcher. */ public boolean simpleMode = false; - + /** - * Constructs an empty loadable. - * The mode is INVALID. + * Constructs an empty loadable. The mode is INVALID. */ public Loadable() { } - + /** * Quick constructor for a board loadable. + * * @param board */ public Loadable(String board) { @@ -54,9 +54,10 @@ public class Loadable { this.board = board; no = 0; } - + /** * Quick constructor for a thread loadable. + * * @param board * @param no */ @@ -65,9 +66,10 @@ public class Loadable { this.board = board; this.no = no; } - + /** * Quick constructor for a thread loadable with an title. + * * @param board * @param no * @param title @@ -78,34 +80,32 @@ public class Loadable { this.no = no; this.title = title; } - + /** * Does not compare the title. */ @Override public boolean equals(Object object) { - if (!(object instanceof Loadable)) return false; - + if (!(object instanceof Loadable)) + return false; + Loadable other = (Loadable) object; - - return - mode == other.mode && - board.equals(other.board) && - no == other.no; + + return mode == other.mode && board.equals(other.board) && no == other.no; } - + public boolean isBoardMode() { return mode == Mode.BOARD; } - + public boolean isThreadMode() { return mode == Mode.THREAD; } - + public boolean isCatalogMode() { return mode == Mode.CATALOG; } - + public void readFromBundle(Context context, Bundle bundle) { String p = context.getPackageName(); mode = bundle.getInt(p + ".mode", Mode.INVALID); @@ -115,7 +115,7 @@ public class Loadable { listViewIndex = bundle.getInt(p + ".listViewIndex"); listViewTop = bundle.getInt(p + ".listViewTop"); } - + public void writeToBundle(Context context, Bundle bundle) { String p = context.getPackageName(); bundle.putInt(p + ".mode", mode); @@ -125,7 +125,7 @@ public class Loadable { bundle.putInt(p + ".listViewIndex", listViewIndex); bundle.putInt(p + ".listViewTop", listViewTop); } - + public void readFromBundle(Context context, String tag, Bundle bundle) { String p = context.getPackageName(); mode = bundle.getInt(p + "." + tag + ".mode", Mode.INVALID); @@ -135,7 +135,7 @@ public class Loadable { listViewIndex = bundle.getInt(p + "." + tag + ".listViewIndex"); listViewTop = bundle.getInt(p + "." + tag + ".listViewTop"); } - + public void writeToBundle(Context context, String tag, Bundle bundle) { String p = context.getPackageName(); bundle.putInt(p + "." + tag + ".mode", mode); @@ -145,7 +145,7 @@ public class Loadable { bundle.putInt(p + "." + tag + ".listViewIndex", listViewIndex); bundle.putInt(p + "." + tag + ".listViewTop", listViewTop); } - + public Loadable copy() { Loadable copy = new Loadable(); copy.mode = mode; @@ -155,10 +155,10 @@ public class Loadable { copy.listViewIndex = listViewIndex; copy.listViewTop = listViewTop; copy.simpleMode = simpleMode; - + return copy; } - + public static class Mode { public static final int INVALID = -1; public static final int THREAD = 0; @@ -166,8 +166,3 @@ public class Loadable { public static final int CATALOG = 2; } } - - - - - diff --git a/Chan/src/org/floens/chan/core/model/Pin.java b/Chan/src/org/floens/chan/core/model/Pin.java index 69329740..1c652196 100644 --- a/Chan/src/org/floens/chan/core/model/Pin.java +++ b/Chan/src/org/floens/chan/core/model/Pin.java @@ -17,9 +17,9 @@ public class Pin { // ListView Stuff /** Header is used to display a static header in the drawer listview. */ public Type type = Type.THREAD; + public static enum Type { - HEADER, - THREAD + HEADER, THREAD }; // PinnedService stuff @@ -33,19 +33,19 @@ public class Pin { @DatabaseField public int watchNewCount; - + @DatabaseField public int quoteLastCount; - + @DatabaseField public int quoteNewCount; - + public boolean isError = false; public PinWatcher getPinWatcher() { return pinWatcher; } - + public int getNewPostsCount() { if (watchLastCount <= 0) { return 0; @@ -53,7 +53,7 @@ public class Pin { return Math.max(0, watchNewCount - watchLastCount); } } - + public int getNewQuoteCount() { if (quoteLastCount <= 0) { return 0; @@ -61,7 +61,7 @@ public class Pin { return Math.max(0, quoteNewCount - quoteLastCount); } } - + public Post getLastSeenPost() { if (pinWatcher == null) { return null; @@ -85,6 +85,3 @@ public class Pin { } } } - - - diff --git a/Chan/src/org/floens/chan/core/model/Post.java b/Chan/src/org/floens/chan/core/model/Post.java index 30fcdd4e..7409d430 100644 --- a/Chan/src/org/floens/chan/core/model/Post.java +++ b/Chan/src/org/floens/chan/core/model/Post.java @@ -95,7 +95,7 @@ public class Post { /** * Finish up the data - * + * * @return false if this data is invalid */ public boolean finish(Loadable loadable) { diff --git a/Chan/src/org/floens/chan/core/model/PostLinkable.java b/Chan/src/org/floens/chan/core/model/PostLinkable.java index af4553af..6ef70515 100644 --- a/Chan/src/org/floens/chan/core/model/PostLinkable.java +++ b/Chan/src/org/floens/chan/core/model/PostLinkable.java @@ -9,7 +9,9 @@ import android.view.View; * Anything that links to something in a post uses this entity. */ public class PostLinkable extends ClickableSpan { - public static enum Type {QUOTE, LINK}; + public static enum Type { + QUOTE, LINK + }; public final Post post; public final String key; diff --git a/Chan/src/org/floens/chan/core/model/SavedReply.java b/Chan/src/org/floens/chan/core/model/SavedReply.java index 6ec55cda..d61551b5 100644 --- a/Chan/src/org/floens/chan/core/model/SavedReply.java +++ b/Chan/src/org/floens/chan/core/model/SavedReply.java @@ -7,13 +7,13 @@ import com.j256.ormlite.table.DatabaseTable; public class SavedReply { @DatabaseField(generatedId = true) private int id; - + @DatabaseField public String board = ""; - + @DatabaseField public int no; - + @DatabaseField public String password = ""; } diff --git a/Chan/src/org/floens/chan/core/net/BitmapLruImageCache.java b/Chan/src/org/floens/chan/core/net/BitmapLruImageCache.java index ebacf92c..9037f815 100644 --- a/Chan/src/org/floens/chan/core/net/BitmapLruImageCache.java +++ b/Chan/src/org/floens/chan/core/net/BitmapLruImageCache.java @@ -7,21 +7,21 @@ import com.android.volley.toolbox.ImageLoader.ImageCache; public class BitmapLruImageCache extends LruCache implements ImageCache { public BitmapLruImageCache(int maxSize) { - super(maxSize); + super(maxSize); } @Override protected int sizeOf(String key, Bitmap value) { - return value.getRowBytes() * value.getHeight(); + return value.getRowBytes() * value.getHeight(); } @Override public Bitmap getBitmap(String url) { - return get(url); + return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { - put(url, bitmap); + put(url, bitmap); } } \ No newline at end of file diff --git a/Chan/src/org/floens/chan/core/net/BoardsRequest.java b/Chan/src/org/floens/chan/core/net/BoardsRequest.java index e398a6c9..1d09f8db 100644 --- a/Chan/src/org/floens/chan/core/net/BoardsRequest.java +++ b/Chan/src/org/floens/chan/core/net/BoardsRequest.java @@ -14,7 +14,7 @@ public class BoardsRequest extends JsonReaderRequest> { public BoardsRequest(String url, Listener> listener, ErrorListener errorListener) { super(url, listener, errorListener); } - + @Override public ArrayList readJson(JsonReader reader) { return parseJson(reader); @@ -22,49 +22,49 @@ public class BoardsRequest extends JsonReaderRequest> { private ArrayList parseJson(JsonReader reader) { ArrayList list = new ArrayList(); - + try { - reader.beginObject(); + reader.beginObject(); // Page object while (reader.hasNext()) { String key = reader.nextName(); if (key.equals("boards")) { reader.beginArray(); - - while(reader.hasNext()) { + + while (reader.hasNext()) { list.add(readBoardEntry(reader)); } - + reader.endArray(); } else { throw new IOException("Invalid data received"); } } reader.endObject(); - } catch(IOException e) { + } catch (IOException e) { e.printStackTrace(); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { e.printStackTrace(); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { e.printStackTrace(); } - + return list; } - + @Override public Priority getPriority() { return Priority.LOW; } - + private Board readBoardEntry(JsonReader reader) throws IOException { reader.beginObject(); - + Board board = new Board(); - - while(reader.hasNext()) { + + while (reader.hasNext()) { String key = reader.nextName(); - + if (key.equals("title")) { // Post number board.key = reader.nextString(); @@ -78,13 +78,13 @@ public class BoardsRequest extends JsonReaderRequest> { reader.skipValue(); } } - + reader.endObject(); - + if (!board.finish()) { throw new IOException("Invalid data received about boards."); } - + return board; } } diff --git a/Chan/src/org/floens/chan/core/net/ByteArrayRequest.java b/Chan/src/org/floens/chan/core/net/ByteArrayRequest.java index 17930657..ebaeaa80 100644 --- a/Chan/src/org/floens/chan/core/net/ByteArrayRequest.java +++ b/Chan/src/org/floens/chan/core/net/ByteArrayRequest.java @@ -7,26 +7,24 @@ import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; /** - * Request a plain byte[] - * Warning: no caching! + * Request a plain byte[] Warning: no caching! */ public class ByteArrayRequest extends Request { protected final Listener listener; - + public ByteArrayRequest(String url, Listener listener, ErrorListener errorListener) { super(Method.GET, url, errorListener); - + this.listener = listener; } - + @Override protected void deliverResponse(byte[] response) { listener.onResponse(response); } - + @Override protected Response parseNetworkResponse(NetworkResponse response) { return Response.success(response.data, null); } } - diff --git a/Chan/src/org/floens/chan/core/net/ChanReaderRequest.java b/Chan/src/org/floens/chan/core/net/ChanReaderRequest.java index b18a7935..268cdc95 100644 --- a/Chan/src/org/floens/chan/core/net/ChanReaderRequest.java +++ b/Chan/src/org/floens/chan/core/net/ChanReaderRequest.java @@ -25,14 +25,19 @@ public class ChanReaderRequest extends JsonReaderRequest> { /** * Creates a ChanReaderRequest with supplied params - * @param mode ThreadManager mode - * @param board board key - * @param no page for board, no for threads + * + * @param mode + * ThreadManager mode + * @param board + * board key + * @param no + * page for board, no for threads * @param listener * @param errorListener * @return New instance of ChanReaderRequest */ - public static ChanReaderRequest newInstance(Loadable loadable, List cached, Listener> listener, ErrorListener errorListener) { + public static ChanReaderRequest newInstance(Loadable loadable, List cached, Listener> listener, + ErrorListener errorListener) { String url; if (loadable.isBoardMode()) { @@ -110,13 +115,13 @@ public class ChanReaderRequest extends JsonReaderRequest> { } } reader.endObject(); - } catch(IOException e) { + } catch (IOException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { e.printStackTrace(); setError(new ParseError(e)); } @@ -142,7 +147,8 @@ public class ChanReaderRequest extends JsonReaderRequest> { list.add(readPostObject(reader)); // Only consume one post - while (reader.hasNext()) reader.skipValue(); + while (reader.hasNext()) + reader.skipValue(); reader.endArray(); } else { @@ -158,13 +164,13 @@ public class ChanReaderRequest extends JsonReaderRequest> { } reader.endObject(); - } catch(IOException e) { + } catch (IOException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { e.printStackTrace(); setError(new ParseError(e)); } @@ -199,13 +205,13 @@ public class ChanReaderRequest extends JsonReaderRequest> { } reader.endArray(); - } catch(IOException e) { + } catch (IOException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { e.printStackTrace(); setError(new ParseError(e)); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { e.printStackTrace(); setError(new ParseError(e)); } @@ -218,16 +224,16 @@ public class ChanReaderRequest extends JsonReaderRequest> { post.board = loadable.board; reader.beginObject(); - while(reader.hasNext()) { + while (reader.hasNext()) { String key = reader.nextName(); if (key.equals("no")) { // Post number post.no = reader.nextInt(); - /*} else if (key.equals("time")) { - // Time - long time = reader.nextLong(); - post.date = new Date(time * 1000);*/ + /*} else if (key.equals("time")) { + // Time + long time = reader.nextLong(); + post.date = new Date(time * 1000);*/ } else if (key.equals("now")) { post.date = reader.nextString(); } else if (key.equals("name")) { @@ -270,7 +276,7 @@ public class ChanReaderRequest extends JsonReaderRequest> { post.capcode = reader.nextString(); } else { // Unknown/ignored key -// log("Unknown/ignored key: " + key + "."); + // log("Unknown/ignored key: " + key + "."); reader.skipValue(); } } @@ -295,8 +301,3 @@ public class ChanReaderRequest extends JsonReaderRequest> { } } } - - - - - diff --git a/Chan/src/org/floens/chan/core/net/FileRequest.java b/Chan/src/org/floens/chan/core/net/FileRequest.java index 172329b5..6452a8fd 100644 --- a/Chan/src/org/floens/chan/core/net/FileRequest.java +++ b/Chan/src/org/floens/chan/core/net/FileRequest.java @@ -18,7 +18,7 @@ public class FileRequest extends Request { public FileRequest(String url, Listener listener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.listener = listener; - + setShouldCache(true); } diff --git a/Chan/src/org/floens/chan/core/net/GIFRequest.java b/Chan/src/org/floens/chan/core/net/GIFRequest.java index 400f64a5..95d32e40 100644 --- a/Chan/src/org/floens/chan/core/net/GIFRequest.java +++ b/Chan/src/org/floens/chan/core/net/GIFRequest.java @@ -15,24 +15,24 @@ import com.android.volley.toolbox.HttpHeaderParser; public class GIFRequest extends Request { protected final Listener listener; private final Context context; - + public GIFRequest(String url, Listener listener, ErrorListener errorListener, Context context) { super(Method.GET, url, errorListener); - + this.listener = listener; this.context = context; } - + @Override protected void deliverResponse(GIFView response) { listener.onResponse(response); } - + @Override protected Response parseNetworkResponse(NetworkResponse response) { GIFView gifView = new GIFView(context); boolean success = gifView.setData(response.data); - + if (success) { return Response.success(gifView, HttpHeaderParser.parseCacheHeaders(response)); } else { @@ -40,7 +40,3 @@ public class GIFRequest extends Request { } } } - - - - diff --git a/Chan/src/org/floens/chan/core/net/JsonReaderRequest.java b/Chan/src/org/floens/chan/core/net/JsonReaderRequest.java index 9ec1acac..654d8f71 100644 --- a/Chan/src/org/floens/chan/core/net/JsonReaderRequest.java +++ b/Chan/src/org/floens/chan/core/net/JsonReaderRequest.java @@ -68,7 +68,3 @@ public abstract class JsonReaderRequest extends Request { public abstract T readJson(JsonReader reader); } - - - - diff --git a/Chan/src/org/floens/chan/database/DatabaseHelper.java b/Chan/src/org/floens/chan/database/DatabaseHelper.java index dd91efe1..c968692e 100644 --- a/Chan/src/org/floens/chan/database/DatabaseHelper.java +++ b/Chan/src/org/floens/chan/database/DatabaseHelper.java @@ -55,7 +55,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { - switch(oldVersion) { + switch (oldVersion) { // Change tables if we make adjustments } @@ -83,8 +83,3 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } } - - - - - diff --git a/Chan/src/org/floens/chan/database/DatabaseManager.java b/Chan/src/org/floens/chan/database/DatabaseManager.java index c93f8eb5..bea54329 100644 --- a/Chan/src/org/floens/chan/database/DatabaseManager.java +++ b/Chan/src/org/floens/chan/database/DatabaseManager.java @@ -95,7 +95,7 @@ public class DatabaseManager { for (Pin pin : pins) { helper.loadableDao.update(pin.loadable); } - } catch(SQLException e) { + } catch (SQLException e) { Logger.e(TAG, "Error updating pins in db", e); } } @@ -103,10 +103,10 @@ public class DatabaseManager { public List getPinned() { List list = null; try { - list = helper.pinDao.queryForAll(); - for (Pin p : list) { - helper.loadableDao.refresh(p.loadable); - } + list = helper.pinDao.queryForAll(); + for (Pin p : list) { + helper.loadableDao.refresh(p.loadable); + } } catch (SQLException e) { Logger.e(TAG, "Error getting pins from db", e); } @@ -133,8 +133,3 @@ public class DatabaseManager { loadSavedReplies(); } } - - - - - diff --git a/Chan/src/org/floens/chan/service/WatchService.java b/Chan/src/org/floens/chan/service/WatchService.java index 84a1f853..2c073c8d 100644 --- a/Chan/src/org/floens/chan/service/WatchService.java +++ b/Chan/src/org/floens/chan/service/WatchService.java @@ -190,7 +190,7 @@ public class WatchService extends Service { /** * Returns the sleep time the user specified for background iteration - * + * * @return the sleep time in ms, or -1 if background reloading is disabled */ private long getBackgroundTimeout() { diff --git a/Chan/src/org/floens/chan/ui/ScrollerRunnable.java b/Chan/src/org/floens/chan/ui/ScrollerRunnable.java index b7d2182d..d0366dbe 100644 --- a/Chan/src/org/floens/chan/ui/ScrollerRunnable.java +++ b/Chan/src/org/floens/chan/ui/ScrollerRunnable.java @@ -26,12 +26,12 @@ public class ScrollerRunnable implements Runnable { final int firstPos = mList.getFirstVisiblePosition(); final int lastPos = firstPos + mList.getChildCount() - 1; -// int viewTravelCount = 0; + // int viewTravelCount = 0; if (position <= firstPos) { -// viewTravelCount = firstPos - position + 1; + // viewTravelCount = firstPos - position + 1; mMode = MOVE_UP_POS; } else if (position >= lastPos) { -// viewTravelCount = position - lastPos + 1; + // viewTravelCount = position - lastPos + 1; mMode = MOVE_DOWN_POS; } else { // Already on screen, nothing to do @@ -64,8 +64,8 @@ public class ScrollerRunnable implements Runnable { if (lastPos == mLastSeenPos) { // No new views, let things keep going. -// mList.post(this); -// return; + // mList.post(this); + // return; } final View lastView = mList.getChildAt(lastViewIndex); @@ -86,8 +86,8 @@ public class ScrollerRunnable implements Runnable { case MOVE_UP_POS: { if (firstPos == mLastSeenPos) { // No new views, let things keep going. -// mList.post(this); -// return; + // mList.post(this); + // return; } final View firstView = mList.getChildAt(0); diff --git a/Chan/src/org/floens/chan/ui/SwipeDismissListViewTouchListener.java b/Chan/src/org/floens/chan/ui/SwipeDismissListViewTouchListener.java index d11e7d31..0c619314 100644 --- a/Chan/src/org/floens/chan/ui/SwipeDismissListViewTouchListener.java +++ b/Chan/src/org/floens/chan/ui/SwipeDismissListViewTouchListener.java @@ -33,37 +33,44 @@ import android.widget.AbsListView; import android.widget.ListView; /** - * A {@link android.view.View.OnTouchListener} that makes the list items in a {@link ListView} - * dismissable. {@link ListView} is given special treatment because by default it handles touches - * for its list items... i.e. it's in charge of drawing the pressed state (the list selector), - * handling list item clicks, etc. - * - *

After creating the listener, the caller should also call {@link - * ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}, passing in the scroll - * listener returned by {@link #makeScrollListener()}. If a scroll listener is already assigned, the - * caller should still pass scroll changes through to this listener. This will ensure that this - * {@link SwipeDismissListViewTouchListener} is paused during list view scrolling.

- * - *

Example usage:

- * + * A {@link android.view.View.OnTouchListener} that makes the list items in a + * {@link ListView} dismissable. {@link ListView} is given special treatment + * because by default it handles touches for its list items... i.e. it's in + * charge of drawing the pressed state (the list selector), handling list item + * clicks, etc. + * + *

+ * After creating the listener, the caller should also call + * {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)} + * , passing in the scroll listener returned by {@link #makeScrollListener()}. + * If a scroll listener is already assigned, the caller should still pass scroll + * changes through to this listener. This will ensure that this + * {@link SwipeDismissListViewTouchListener} is paused during list view + * scrolling. + *

+ * + *

+ * Example usage: + *

+ * *
- * SwipeDismissListViewTouchListener touchListener =
- *         new SwipeDismissListViewTouchListener(
- *                 listView,
- *                 new SwipeDismissListViewTouchListener.OnDismissCallback() {
- *                     public void onDismiss(ListView listView, int[] reverseSortedPositions) {
- *                         for (int position : reverseSortedPositions) {
- *                             adapter.remove(adapter.getItem(position));
- *                         }
- *                         adapter.notifyDataSetChanged();
- *                     }
- *                 });
+ * SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(listView,
+ *         new SwipeDismissListViewTouchListener.OnDismissCallback() {
+ *             public void onDismiss(ListView listView, int[] reverseSortedPositions) {
+ *                 for (int position : reverseSortedPositions) {
+ *                     adapter.remove(adapter.getItem(position));
+ *                 }
+ *                 adapter.notifyDataSetChanged();
+ *             }
+ *         });
  * listView.setOnTouchListener(touchListener);
  * listView.setOnScrollListener(touchListener.makeScrollListener());
  * 
- * - *

This class Requires API level 12 or later due to use of {@link - * android.view.ViewPropertyAnimator}.

+ * + *

+ * This class Requires API level 12 or later due to use of + * {@link android.view.ViewPropertyAnimator}. + *

*/ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values @@ -88,8 +95,9 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { private boolean mPaused; /** - * The callback interface used by {@link SwipeDismissListViewTouchListener} to inform its client - * about a successful dismissal of one or more list item positions. + * The callback interface used by {@link SwipeDismissListViewTouchListener} + * to inform its client about a successful dismissal of one or more list + * item positions. */ public interface DismissCallbacks { /** @@ -98,50 +106,57 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { boolean canDismiss(int position); /** - * Called when the user has indicated they she would like to dismiss one or more list item - * positions. - * - * @param listView The originating {@link ListView}. - * @param reverseSortedPositions An array of positions to dismiss, sorted in descending - * order for convenience. + * Called when the user has indicated they she would like to dismiss one + * or more list item positions. + * + * @param listView + * The originating {@link ListView}. + * @param reverseSortedPositions + * An array of positions to dismiss, sorted in descending + * order for convenience. */ void onDismiss(ListView listView, int[] reverseSortedPositions); } /** * Constructs a new swipe-to-dismiss touch listener for the given list view. - * - * @param listView The list view whose items should be dismissable. - * @param callbacks The callback to trigger when the user has indicated that she would like to - * dismiss one or more list items. + * + * @param listView + * The list view whose items should be dismissable. + * @param callbacks + * The callback to trigger when the user has indicated that she + * would like to dismiss one or more list items. */ public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) { ViewConfiguration vc = ViewConfiguration.get(listView.getContext()); - mSlop = Math.max(1, (int)(vc.getScaledTouchSlop() * 0.5f)); + mSlop = Math.max(1, (int) (vc.getScaledTouchSlop() * 0.5f)); mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16; mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); - mAnimationTime = listView.getContext().getResources().getInteger( - android.R.integer.config_shortAnimTime); + mAnimationTime = listView.getContext().getResources().getInteger(android.R.integer.config_shortAnimTime); mListView = listView; mCallbacks = callbacks; } /** - * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures. - * - * @param enabled Whether or not to watch for gestures. + * Enables or disables (pauses or resumes) watching for swipe-to-dismiss + * gestures. + * + * @param enabled + * Whether or not to watch for gestures. */ public void setEnabled(boolean enabled) { mPaused = !enabled; } /** - * Returns an {@link android.widget.AbsListView.OnScrollListener} to be added to the {@link - * ListView} using {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}. - * If a scroll listener is already assigned, the caller should still pass scroll changes through - * to this listener. This will ensure that this {@link SwipeDismissListViewTouchListener} is - * paused during list view scrolling.

- * + * Returns an {@link android.widget.AbsListView.OnScrollListener} to be + * added to the {@link ListView} using + * {@link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)} + * . If a scroll listener is already assigned, the caller should still pass + * scroll changes through to this listener. This will ensure that this + * {@link SwipeDismissListViewTouchListener} is paused during list view + * scrolling.

+ * * @see SwipeDismissListViewTouchListener */ public AbsListView.OnScrollListener makeScrollListener() { @@ -158,8 +173,8 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { } /** - * Manually cause the item at the given position to be dismissed (trigger the dismiss - * animation). + * Manually cause the item at the given position to be dismissed (trigger + * the dismiss animation). */ public void dismiss(int position) { dismiss(getViewForPosition(position), position, true); @@ -172,136 +187,126 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { } switch (motionEvent.getActionMasked()) { - case MotionEvent.ACTION_DOWN: { - if (mPaused) { - return false; - } - - // TODO: ensure this is a finger, and set a flag - - // Find the child view that was touched (perform a hit test) - Rect rect = new Rect(); - int childCount = mListView.getChildCount(); - int[] listViewCoords = new int[2]; - mListView.getLocationOnScreen(listViewCoords); - int x = (int) motionEvent.getRawX() - listViewCoords[0]; - int y = (int) motionEvent.getRawY() - listViewCoords[1]; - View child; - for (int i = 0; i < childCount; i++) { - child = mListView.getChildAt(i); - child.getHitRect(rect); - if (rect.contains(x, y)) { - mDownView = child; - break; - } - } - - if (mDownView != null) { - mDownX = motionEvent.getRawX(); - mDownPosition = mListView.getPositionForView(mDownView); - if (mCallbacks.canDismiss(mDownPosition)) { - mVelocityTracker = VelocityTracker.obtain(); - mVelocityTracker.addMovement(motionEvent); - } else { - mDownView = null; - } - } - view.onTouchEvent(motionEvent); - return true; + case MotionEvent.ACTION_DOWN: { + if (mPaused) { + return false; } - case MotionEvent.ACTION_UP: { - if (mVelocityTracker == null) { + // TODO: ensure this is a finger, and set a flag + + // Find the child view that was touched (perform a hit test) + Rect rect = new Rect(); + int childCount = mListView.getChildCount(); + int[] listViewCoords = new int[2]; + mListView.getLocationOnScreen(listViewCoords); + int x = (int) motionEvent.getRawX() - listViewCoords[0]; + int y = (int) motionEvent.getRawY() - listViewCoords[1]; + View child; + for (int i = 0; i < childCount; i++) { + child = mListView.getChildAt(i); + child.getHitRect(rect); + if (rect.contains(x, y)) { + mDownView = child; break; } + } - float deltaX = motionEvent.getRawX() - mDownX; - mVelocityTracker.addMovement(motionEvent); - mVelocityTracker.computeCurrentVelocity(1000); - float velocityX = mVelocityTracker.getXVelocity(); - float absVelocityX = Math.abs(velocityX); - float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); - boolean dismiss = false; - boolean dismissRight = false; - if (Math.abs(deltaX) > mViewWidth / 2) { - dismiss = true; - dismissRight = deltaX > 0; - } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity - && absVelocityY < absVelocityX) { - // dismiss only if flinging in the same direction as dragging - dismiss = (velocityX < 0) == (deltaX < 0); - dismissRight = mVelocityTracker.getXVelocity() > 0; - } - if (dismiss) { - // dismiss - dismiss(mDownView, mDownPosition, dismissRight); + if (mDownView != null) { + mDownX = motionEvent.getRawX(); + mDownPosition = mListView.getPositionForView(mDownView); + if (mCallbacks.canDismiss(mDownPosition)) { + mVelocityTracker = VelocityTracker.obtain(); + mVelocityTracker.addMovement(motionEvent); } else { - // cancel - mDownView.animate() - .translationX(0) - .alpha(1) - .setDuration(mAnimationTime) - .setListener(null); + mDownView = null; } - mVelocityTracker.recycle(); - mVelocityTracker = null; - mDownX = 0; - mDownView = null; - mDownPosition = ListView.INVALID_POSITION; - mSwiping = false; + } + view.onTouchEvent(motionEvent); + return true; + } + + case MotionEvent.ACTION_UP: { + if (mVelocityTracker == null) { break; } - case MotionEvent.ACTION_CANCEL: { - if (mVelocityTracker == null) { - break; - } + float deltaX = motionEvent.getRawX() - mDownX; + mVelocityTracker.addMovement(motionEvent); + mVelocityTracker.computeCurrentVelocity(1000); + float velocityX = mVelocityTracker.getXVelocity(); + float absVelocityX = Math.abs(velocityX); + float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); + boolean dismiss = false; + boolean dismissRight = false; + if (Math.abs(deltaX) > mViewWidth / 2) { + dismiss = true; + dismissRight = deltaX > 0; + } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity + && absVelocityY < absVelocityX) { + // dismiss only if flinging in the same direction as dragging + dismiss = (velocityX < 0) == (deltaX < 0); + dismissRight = mVelocityTracker.getXVelocity() > 0; + } + if (dismiss) { + // dismiss + dismiss(mDownView, mDownPosition, dismissRight); + } else { + // cancel + mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); + } + mVelocityTracker.recycle(); + mVelocityTracker = null; + mDownX = 0; + mDownView = null; + mDownPosition = ListView.INVALID_POSITION; + mSwiping = false; + break; + } - if (mDownView != null) { - // cancel - mDownView.animate() - .translationX(0) - .alpha(1) - .setDuration(mAnimationTime) - .setListener(null); - } - mVelocityTracker.recycle(); - mVelocityTracker = null; - mDownX = 0; - mDownView = null; - mDownPosition = ListView.INVALID_POSITION; - mSwiping = false; + case MotionEvent.ACTION_CANCEL: { + if (mVelocityTracker == null) { break; } - case MotionEvent.ACTION_MOVE: { - if (mVelocityTracker == null || mPaused) { - break; - } - - mVelocityTracker.addMovement(motionEvent); - float deltaX = motionEvent.getRawX() - mDownX; - if (Math.abs(deltaX) > mSlop) { - mSwiping = true; - mListView.requestDisallowInterceptTouchEvent(true); - - // Cancel ListView's touch (un-highlighting the item) - MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); - cancelEvent.setAction(MotionEvent.ACTION_CANCEL | - (motionEvent.getActionIndex() - << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); - mListView.onTouchEvent(cancelEvent); - cancelEvent.recycle(); - } + if (mDownView != null) { + // cancel + mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); + } + mVelocityTracker.recycle(); + mVelocityTracker = null; + mDownX = 0; + mDownView = null; + mDownPosition = ListView.INVALID_POSITION; + mSwiping = false; + break; + } - if (mSwiping) { - mDownView.setTranslationX(deltaX); - mDownView.setAlpha(Math.max(0.15f, Math.min(1f, - 1f - 2f * Math.abs(deltaX) / mViewWidth))); - return true; - } + case MotionEvent.ACTION_MOVE: { + if (mVelocityTracker == null || mPaused) { break; } + + mVelocityTracker.addMovement(motionEvent); + float deltaX = motionEvent.getRawX() - mDownX; + if (Math.abs(deltaX) > mSlop) { + mSwiping = true; + mListView.requestDisallowInterceptTouchEvent(true); + + // Cancel ListView's touch (un-highlighting the item) + MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); + cancelEvent.setAction(MotionEvent.ACTION_CANCEL + | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); + mListView.onTouchEvent(cancelEvent); + cancelEvent.recycle(); + } + + if (mSwiping) { + mDownView.setTranslationX(deltaX); + mDownView.setAlpha(Math.max(0.15f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); + return true; + } + break; + } } return false; } @@ -315,10 +320,7 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { return; } - view.animate() - .translationX(dismissRight ? mViewWidth : -mViewWidth) - .alpha(0) - .setDuration(mAnimationTime) + view.animate().translationX(dismissRight ? mViewWidth : -mViewWidth).alpha(0).setDuration(mAnimationTime) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { @@ -328,11 +330,8 @@ public class SwipeDismissListViewTouchListener implements View.OnTouchListener { } private View getViewForPosition(int position) { - int index = position - - (mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount()); - return (index >= 0 && index < mListView.getChildCount()) - ? mListView.getChildAt(index) - : null; + int index = position - (mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount()); + return (index >= 0 && index < mListView.getChildCount()) ? mListView.getChildAt(index) : null; } class PendingDismissData implements Comparable { diff --git a/Chan/src/org/floens/chan/ui/ViewFlipperAnimations.java b/Chan/src/org/floens/chan/ui/ViewFlipperAnimations.java index 7db18757..dbf834a4 100644 --- a/Chan/src/org/floens/chan/ui/ViewFlipperAnimations.java +++ b/Chan/src/org/floens/chan/ui/ViewFlipperAnimations.java @@ -12,38 +12,26 @@ public class ViewFlipperAnimations { public static TranslateAnimation BACK_OUT; public static TranslateAnimation NEXT_IN; public static TranslateAnimation NEXT_OUT; - + static { // Setup the static TranslateAnimations for the ViewFlipper - BACK_IN = new TranslateAnimation( - Animation.RELATIVE_TO_PARENT, -1f, - Animation.RELATIVE_TO_PARENT, 0f, - 0, 0f, 0, 0f - ); + BACK_IN = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1f, Animation.RELATIVE_TO_PARENT, 0f, 0, 0f, 0, + 0f); BACK_IN.setInterpolator(new AccelerateDecelerateInterpolator()); BACK_IN.setDuration(300); - - BACK_OUT = new TranslateAnimation( - Animation.RELATIVE_TO_PARENT, 0f, - Animation.RELATIVE_TO_PARENT, 1f, - 0, 0f, 0, 0f - ); + + BACK_OUT = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 1f, 0, 0f, 0, + 0f); BACK_OUT.setInterpolator(new AccelerateDecelerateInterpolator()); BACK_OUT.setDuration(300); - - NEXT_IN = new TranslateAnimation( - Animation.RELATIVE_TO_PARENT, 1f, - Animation.RELATIVE_TO_PARENT, 0f, - 0, 0f, 0, 0f - ); + + NEXT_IN = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1f, Animation.RELATIVE_TO_PARENT, 0f, 0, 0f, 0, + 0f); NEXT_IN.setInterpolator(new AccelerateDecelerateInterpolator()); NEXT_IN.setDuration(300); - - NEXT_OUT = new TranslateAnimation( - Animation.RELATIVE_TO_PARENT, 0f, - Animation.RELATIVE_TO_PARENT, -1f, - 0, 0f, 0, 0f - ); + + NEXT_OUT = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, -1f, 0, 0f, + 0, 0f); NEXT_OUT.setInterpolator(new AccelerateDecelerateInterpolator()); NEXT_OUT.setDuration(300); } diff --git a/Chan/src/org/floens/chan/ui/activity/AboutActivity.java b/Chan/src/org/floens/chan/ui/activity/AboutActivity.java index 9ed00645..8a746e1a 100644 --- a/Chan/src/org/floens/chan/ui/activity/AboutActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/AboutActivity.java @@ -8,10 +8,10 @@ public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - + WebView webView = new WebView(this); webView.loadUrl("file:///android_asset/html/licences.html"); - + setContentView(webView); } } diff --git a/Chan/src/org/floens/chan/ui/activity/BoardEditor.java b/Chan/src/org/floens/chan/ui/activity/BoardEditor.java index bb2d1a1c..29a7b796 100644 --- a/Chan/src/org/floens/chan/ui/activity/BoardEditor.java +++ b/Chan/src/org/floens/chan/ui/activity/BoardEditor.java @@ -26,104 +26,100 @@ public class BoardEditor extends Activity { private DynamicListView listView; private BoardEditAdapter adapter; private AlertDialog dialog; - + @SuppressWarnings("unchecked") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - + setContentView(R.layout.board_edit); - + // Copy not a reference list = (ArrayList) ChanApplication.getBoardManager().getMyBoards().clone(); - + adapter = new BoardEditAdapter(this, R.layout.board_view, list, this); listView = (DynamicListView) findViewById(R.id.board_edit_list); - + listView.setArrayList(list); listView.setAdapter(adapter); } - + @SuppressWarnings("unchecked") @Override protected void onPause() { super.onPause(); - + // For runtime changes if (list.size() > 0) { ChanApplication.getBoardManager().setMyBoards((ArrayList) list.clone()); } } - + @Override protected void onDestroy() { super.onDestroy(); - + if (dialog != null) { dialog.dismiss(); } } - + private void addBoard(String value) { ChanApplication.getBoardManager().addBoard(list, value); - + adapter = new BoardEditAdapter(this, R.layout.board_view, list, this); listView.setArrayList(list); listView.setAdapter(adapter); } - + private void removeBoard(String value) { - if (list.size() <= 1) return; - + if (list.size() <= 1) + return; + for (int i = 0; i < list.size(); i++) { Board e = list.get(i); if (e.value == value) { list.remove(i); - + adapter = new BoardEditAdapter(this, R.layout.board_view, list, this); listView.setArrayList(list); listView.setAdapter(adapter); } } } - + public void onDeleteClicked(Board board) { removeBoard(board.value); } - + private void showAddBoardDialog() { final EditText text = new EditText(this); text.setSingleLine(); - - dialog = new AlertDialog.Builder(this) - .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { - String value = text.getText().toString(); - - if (!TextUtils.isEmpty(value)) { - addBoard(value); - } - } - }) - .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { + + dialog = new AlertDialog.Builder(this).setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + String value = text.getText().toString(); + + if (!TextUtils.isEmpty(value)) { + addBoard(value); } - }) - .setTitle(R.string.board_add) - .setView(text) - .create(); - + } + }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + } + }).setTitle(R.string.board_add).setView(text).create(); + text.requestFocus(); - + dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface d) { dialog = null; } }); - + dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { @@ -131,30 +127,25 @@ public class BoardEditor extends Activity { imm.showSoftInput(text, 0); } }); - + dialog.show(); } - + @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.board_edit, menu); return true; } - + @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case R.id.action_add_board: showAddBoardDialog(); - + return true; } - + return super.onOptionsItemSelected(item); } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/activity/DeveloperActivity.java b/Chan/src/org/floens/chan/ui/activity/DeveloperActivity.java index 734dcf27..77b228f2 100644 --- a/Chan/src/org/floens/chan/ui/activity/DeveloperActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/DeveloperActivity.java @@ -13,12 +13,12 @@ public class DeveloperActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - + LinearLayout wrapper = new LinearLayout(this); wrapper.setOrientation(LinearLayout.VERTICAL); - + Button crashButton = new Button(this); - + crashButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -27,19 +27,19 @@ public class DeveloperActivity extends Activity { } }); crashButton.setText("Crash the app"); - + wrapper.addView(crashButton); - + String dbSummary = ""; - + dbSummary += "Database summary:\n"; dbSummary += ChanApplication.getDatabaseManager().getSummary(); - + TextView db = new TextView(this); db.setPadding(0, 25, 0, 0); db.setText(dbSummary); wrapper.addView(db); - + Button resetDbButton = new Button(this); resetDbButton.setOnClickListener(new View.OnClickListener() { @Override @@ -50,12 +50,7 @@ public class DeveloperActivity extends Activity { }); resetDbButton.setText("Delete database"); wrapper.addView(resetDbButton); - + setContentView(wrapper); } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/activity/ImagePickActivity.java b/Chan/src/org/floens/chan/ui/activity/ImagePickActivity.java index 873c39c2..36fef59d 100644 --- a/Chan/src/org/floens/chan/ui/activity/ImagePickActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/ImagePickActivity.java @@ -77,8 +77,3 @@ public class ImagePickActivity extends Activity { } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/activity/ImageViewActivity.java b/Chan/src/org/floens/chan/ui/activity/ImageViewActivity.java index 910e8ceb..9f244602 100644 --- a/Chan/src/org/floens/chan/ui/activity/ImageViewActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/ImageViewActivity.java @@ -125,7 +125,7 @@ public class ImageViewActivity extends Activity implements ViewPager.OnPageChang public void invalidateActionBar() { invalidateOptionsMenu(); } - + public void callOnSelect() { ImageViewFragment fragment = getCurrentFragment(); if (fragment != null) { @@ -148,7 +148,7 @@ public class ImageViewActivity extends Activity implements ViewPager.OnPageChang if (fragment != null) { fragment.customOnOptionsItemSelected(item); } - + return super.onOptionsItemSelected(item); } } @@ -156,17 +156,17 @@ public class ImageViewActivity extends Activity implements ViewPager.OnPageChang @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.image_view, menu); - + return true; } - + @Override public boolean onPrepareOptionsMenu(Menu menu) { ImageViewFragment fragment = getCurrentFragment(); if (fragment != null) { fragment.onPrepareOptionsMenu(currentPosition, adapter, menu); } - + return super.onPrepareOptionsMenu(menu); } diff --git a/Chan/src/org/floens/chan/ui/activity/ReplyActivity.java b/Chan/src/org/floens/chan/ui/activity/ReplyActivity.java index 04085c09..a3dea0ab 100644 --- a/Chan/src/org/floens/chan/ui/activity/ReplyActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/ReplyActivity.java @@ -11,40 +11,40 @@ import android.view.MenuItem; public class ReplyActivity extends Activity { private static final String TAG = "ReplyActivity"; - + private static Loadable loadable; - + public static void setLoadable(Loadable l) { loadable = l; } - + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - + if (loadable != null) { getActionBar().setDisplayHomeAsUpEnabled(true); - + FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(android.R.id.content, ReplyFragment.newInstance(loadable)); ft.commitAllowingStateLoss(); - + loadable = null; } else { Logger.e(TAG, "ThreadFragment was null, exiting!"); finish(); } } - + @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case android.R.id.home: finish(); - + return true; } - + return super.onOptionsItemSelected(item); } } diff --git a/Chan/src/org/floens/chan/ui/activity/SettingsActivity.java b/Chan/src/org/floens/chan/ui/activity/SettingsActivity.java index 8baae3cd..23357a03 100644 --- a/Chan/src/org/floens/chan/ui/activity/SettingsActivity.java +++ b/Chan/src/org/floens/chan/ui/activity/SettingsActivity.java @@ -9,7 +9,7 @@ public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - + getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } } diff --git a/Chan/src/org/floens/chan/ui/adapter/BoardEditAdapter.java b/Chan/src/org/floens/chan/ui/adapter/BoardEditAdapter.java index 6d8df16e..133893ab 100644 --- a/Chan/src/org/floens/chan/ui/adapter/BoardEditAdapter.java +++ b/Chan/src/org/floens/chan/ui/adapter/BoardEditAdapter.java @@ -33,13 +33,13 @@ import android.widget.TextView; public class BoardEditAdapter extends ArrayAdapter { HashMap mIdMap = new HashMap(); - + private final BoardEditor editor; public BoardEditAdapter(Context context, int textViewResourceId, List objects, BoardEditor editor) { super(context, textViewResourceId, objects); this.editor = editor; - + for (int i = 0; i < objects.size(); ++i) { mIdMap.put(objects.get(i), i); } @@ -50,30 +50,30 @@ public class BoardEditAdapter extends ArrayAdapter { if (position < 0 || position >= mIdMap.size()) { return -1; } - + Board item = getItem(position); return mIdMap.get(item); } - + @Override public View getView(final int position, View convertView, ViewGroup parent) { String text = getItem(position).key; - + LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - + View view = inflater.inflate(R.layout.board_view, null); - - TextView textView = (TextView)view.findViewById(R.id.board_view_text); + + TextView textView = (TextView) view.findViewById(R.id.board_view_text); textView.setText(text); - - Button button = (Button)view.findViewById(R.id.board_view_delete); + + Button button = (Button) view.findViewById(R.id.board_view_delete); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editor.onDeleteClicked(getItem(position)); } }); - + return view; } @@ -82,4 +82,3 @@ public class BoardEditAdapter extends ArrayAdapter { return true; } } - diff --git a/Chan/src/org/floens/chan/ui/adapter/ImageViewAdapter.java b/Chan/src/org/floens/chan/ui/adapter/ImageViewAdapter.java index b5142126..3d933655 100644 --- a/Chan/src/org/floens/chan/ui/adapter/ImageViewAdapter.java +++ b/Chan/src/org/floens/chan/ui/adapter/ImageViewAdapter.java @@ -12,48 +12,43 @@ import android.support.v13.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; - public class ImageViewAdapter extends FragmentStatePagerAdapter { private final ImageViewActivity activity; private final ArrayList postList = new ArrayList(); - + public ImageViewAdapter(FragmentManager fragmentManager, ImageViewActivity activity) { super(fragmentManager); this.activity = activity; } - + @Override public int getCount() { return postList.size(); } - + @Override public Fragment getItem(int position) { return ImageViewFragment.newInstance(postList.get(position), activity, position); } - + public Post getPost(int position) { - if (position < 0 || position >= getCount()) return null; - + if (position < 0 || position >= getCount()) + return null; + return postList.get(position); } - + @Override public void destroyItem(View collection, int position, Object o) { - View view = (View)o; + View view = (View) o; ((ViewPager) collection).removeView(view); view = null; } - - public void setList(ArrayList list){ + + public void setList(ArrayList list) { postList.clear(); postList.addAll(list); - + notifyDataSetChanged(); } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/adapter/PinnedAdapter.java b/Chan/src/org/floens/chan/ui/adapter/PinnedAdapter.java index 0dc223cc..36054694 100644 --- a/Chan/src/org/floens/chan/ui/adapter/PinnedAdapter.java +++ b/Chan/src/org/floens/chan/ui/adapter/PinnedAdapter.java @@ -49,7 +49,7 @@ public class PinnedAdapter extends ArrayAdapter { frameLayout.setVisibility(View.VISIBLE); TextView itemCount = (TextView) view.findViewById(R.id.drawer_item_count); - + if (item.isError) { itemCount.setText("Err"); } else { diff --git a/Chan/src/org/floens/chan/ui/adapter/PostAdapter.java b/Chan/src/org/floens/chan/ui/adapter/PostAdapter.java index 6fd3ebd6..c18c648d 100644 --- a/Chan/src/org/floens/chan/ui/adapter/PostAdapter.java +++ b/Chan/src/org/floens/chan/ui/adapter/PostAdapter.java @@ -20,7 +20,6 @@ import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; - public class PostAdapter extends BaseAdapter { private final Context context; private final ThreadManager threadManager; @@ -37,7 +36,8 @@ public class PostAdapter extends BaseAdapter { @Override public int getCount() { - if ((threadManager.getLoadable() != null && threadManager.getLoadable().isBoardMode()) || threadManager.shouldWatch()) { + if ((threadManager.getLoadable() != null && threadManager.getLoadable().isBoardMode()) + || threadManager.shouldWatch()) { return postList.size() + 1; } else { return postList.size(); @@ -157,8 +157,3 @@ public class PostAdapter extends BaseAdapter { } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/fragment/PostRepliesFragment.java b/Chan/src/org/floens/chan/ui/fragment/PostRepliesFragment.java index 155e6ffe..8f23cb63 100644 --- a/Chan/src/org/floens/chan/ui/fragment/PostRepliesFragment.java +++ b/Chan/src/org/floens/chan/ui/fragment/PostRepliesFragment.java @@ -17,7 +17,8 @@ import android.widget.ArrayAdapter; import android.widget.ListView; /** - * A DialogFragment that shows a list of posts. Use the newInstance method for instantiating. + * A DialogFragment that shows a list of posts. Use the newInstance method for + * instantiating. */ public class PostRepliesFragment extends DialogFragment { private ListView listView; @@ -119,8 +120,3 @@ public class PostRepliesFragment extends DialogFragment { } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/fragment/ReplyFragment.java b/Chan/src/org/floens/chan/ui/fragment/ReplyFragment.java index f63310d2..a1c15c2b 100644 --- a/Chan/src/org/floens/chan/ui/fragment/ReplyFragment.java +++ b/Chan/src/org/floens/chan/ui/fragment/ReplyFragment.java @@ -46,17 +46,17 @@ import com.micromobs.android.floatlabel.FloatLabelEditText; public class ReplyFragment extends DialogFragment { private static final String TAG = "ReplyFragment"; - + private int page = 0; - + private Loadable loadable; - + private final Reply draft = new Reply(); private boolean shouldSaveDraft = true; - + private boolean gettingCaptcha = false; private String captchaChallenge = ""; - + // Views private View container; private ViewFlipper flipper; @@ -72,129 +72,131 @@ public class ReplyFragment extends DialogFragment { private LoadView captchaContainer; private TextView captchaText; private LoadView responseContainer; - + public static ReplyFragment newInstance(Loadable loadable) { ReplyFragment reply = new ReplyFragment(); reply.loadable = loadable; return reply; } - + @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - + loadable.writeToBundle(getActivity(), outState); } - + @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - + if (loadable == null && savedInstanceState != null) { loadable = new Loadable(); loadable.readFromBundle(getActivity(), savedInstanceState); } - + if (loadable != null) { setClosable(true); - + Dialog dialog = getDialog(); Context context = getActivity(); - String title = loadable.isThreadMode() ? - context.getString(R.string.reply) + " /" + loadable.board + "/" + loadable.no : - context.getString(R.string.reply_to_board) + " /" + loadable.board + "/"; - + String title = loadable.isThreadMode() ? context.getString(R.string.reply) + " /" + loadable.board + "/" + + loadable.no : context.getString(R.string.reply_to_board) + " /" + loadable.board + "/"; + if (dialog == null) { getActivity().getActionBar().setTitle(title); } else { dialog.setTitle(title); } - + if (getDialog() != null) { getDialog().setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { - if (page == 1) flipPage(0); - else if (page == 2) closeReply(); + if (page == 1) + flipPage(0); + else if (page == 2) + closeReply(); return true; - } else return false; + } else + return false; } }); } - + Reply draft = ChanApplication.getReplyManager().getReplyDraft(); - + if (TextUtils.isEmpty(draft.name)) { draft.name = ChanPreferences.getDefaultName(); } - + if (TextUtils.isEmpty(draft.email)) { draft.email = ChanPreferences.getDefaultEmail(); } - + nameView.getEditText().setText(draft.name); emailView.getEditText().setText(draft.email); subjectView.getEditText().setText(draft.subject); commentView.getEditText().setText(draft.comment); setFile(draft.file); - + getCaptcha(); } else { Logger.e(TAG, "Loadable in ReplyFragment was null"); closeReply(); } } - + @Override public void onPause() { super.onPause(); - + ReplyManager replyManager = ChanApplication.getReplyManager(); - + if (shouldSaveDraft) { draft.name = nameView.getText().toString(); draft.email = emailView.getText().toString(); draft.subject = subjectView.getText().toString(); draft.comment = commentView.getText().toString(); - + replyManager.setReplyDraft(draft); } else { replyManager.removeReplyDraft(); setFile(null); } } - + @Override public void onDestroy() { super.onDestroy(); - + ReplyManager replyManager = ChanApplication.getReplyManager(); replyManager.removeFileListener(); } - + @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { // Setup the views with listeners container = inflater.inflate(R.layout.reply_view, null); - flipper = (ViewFlipper)container.findViewById(R.id.reply_flipper); - - nameView = (FloatLabelEditText)container.findViewById(R.id.reply_name); - emailView = (FloatLabelEditText)container.findViewById(R.id.reply_email); - subjectView = (FloatLabelEditText)container.findViewById(R.id.reply_subject); - commentView = (FloatLabelEditText)container.findViewById(R.id.reply_comment); - imageViewContainer = (LoadView)container.findViewById(R.id.reply_image); - responseContainer = (LoadView)container.findViewById(R.id.reply_response); - captchaContainer = (LoadView)container.findViewById(R.id.reply_captcha_container); + flipper = (ViewFlipper) container.findViewById(R.id.reply_flipper); + + nameView = (FloatLabelEditText) container.findViewById(R.id.reply_name); + emailView = (FloatLabelEditText) container.findViewById(R.id.reply_email); + subjectView = (FloatLabelEditText) container.findViewById(R.id.reply_subject); + commentView = (FloatLabelEditText) container.findViewById(R.id.reply_comment); + imageViewContainer = (LoadView) container.findViewById(R.id.reply_image); + responseContainer = (LoadView) container.findViewById(R.id.reply_response); + captchaContainer = (LoadView) container.findViewById(R.id.reply_captcha_container); captchaContainer.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { getCaptcha(); } }); - captchaText = (TextView)container.findViewById(R.id.reply_captcha); - - cancelButton = (Button)container.findViewById(R.id.reply_cancel); + captchaText = (TextView) container.findViewById(R.id.reply_captcha); + + cancelButton = (Button) container.findViewById(R.id.reply_cancel); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { @@ -205,8 +207,8 @@ public class ReplyFragment extends DialogFragment { } } }); - - fileButton = (Button)container.findViewById(R.id.reply_file); + + fileButton = (Button) container.findViewById(R.id.reply_file); fileButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { @@ -215,7 +217,7 @@ public class ReplyFragment extends DialogFragment { public void onFile(File file) { setFile(file); } - + @Override public void onFileLoading() { imageViewContainer.setView(null); @@ -223,16 +225,16 @@ public class ReplyFragment extends DialogFragment { }); } }); - - fileDeleteButton = (Button)container.findViewById(R.id.reply_file_delete); + + fileDeleteButton = (Button) container.findViewById(R.id.reply_file_delete); fileDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { setFile(null); } }); - - submitButton = (Button)container.findViewById(R.id.reply_submit); + + submitButton = (Button) container.findViewById(R.id.reply_submit); submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { @@ -241,13 +243,14 @@ public class ReplyFragment extends DialogFragment { } else if (page == 1) { flipPage(2); submit(); - }; + } + ; } }); - + return container; } - + private void closeReply() { if (getDialog() != null) { dismiss(); @@ -255,9 +258,10 @@ public class ReplyFragment extends DialogFragment { getActivity().finish(); } } - + /** - * Set if the dialog is able to be closed, by pressing outside of the dialog, or something else. + * Set if the dialog is able to be closed, by pressing outside of the + * dialog, or something else. */ private void setClosable(boolean e) { if (getDialog() != null) { @@ -265,17 +269,19 @@ public class ReplyFragment extends DialogFragment { setCancelable(e); } } - + /** - * Flip to an page with an animation. - * Sets the correct text on the cancelButton: - * @param position 0-2 + * Flip to an page with an animation. Sets the correct text on the + * cancelButton: + * + * @param position + * 0-2 */ private void flipPage(int position) { boolean flipBack = position < page; - + page = position; - + if (flipBack) { flipper.setInAnimation(ViewFlipperAnimations.BACK_IN); flipper.setOutAnimation(ViewFlipperAnimations.BACK_OUT); @@ -285,7 +291,7 @@ public class ReplyFragment extends DialogFragment { flipper.setOutAnimation(ViewFlipperAnimations.NEXT_OUT); flipper.showNext(); } - + if (page == 0) { cancelButton.setText(R.string.cancel); } else if (page == 1) { @@ -294,31 +300,32 @@ public class ReplyFragment extends DialogFragment { cancelButton.setText(R.string.close); } } - + /** - * Set the picked image in the imageView. - * Sets the file in the draft. - * Call null on the file to empty the imageView. - * @param imagePath file to image to send or null to clear + * Set the picked image in the imageView. Sets the file in the draft. Call + * null on the file to empty the imageView. + * + * @param imagePath + * file to image to send or null to clear */ private void setFile(final File file) { draft.file = file; - + if (file == null) { fileDeleteButton.setEnabled(false); imageViewContainer.removeAllViews(); } else { fileDeleteButton.setEnabled(true); // UI Thread - + final ImageView imageView = new ImageView(getActivity()); - + new Thread(new Runnable() { @Override public void run() { // Other thread final Bitmap bitmap = ImageDecoder.decodeFile(file, imageViewContainer.getWidth(), 3000); - + getActivity().runOnUiThread(new Runnable() { @Override public void run() { @@ -328,7 +335,7 @@ public class ReplyFragment extends DialogFragment { } else { imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setImageBitmap(bitmap); - + imageViewContainer.setView(imageView); } } @@ -337,29 +344,31 @@ public class ReplyFragment extends DialogFragment { }).start(); } } - + private void getCaptcha() { - if (gettingCaptcha) return; + if (gettingCaptcha) + return; gettingCaptcha = true; - + captchaContainer.setView(null); - + String url = ChanUrls.getCaptchaChallengeUrl(); - + ChanApplication.getVolleyRequestQueue().add(new StringRequest(Method.GET, url, new Response.Listener() { @Override public void onResponse(String result) { - if (!isVisible()) return; - + if (!isVisible()) + return; + String challenge = ReplyManager.getChallenge(result); if (challenge != null) { captchaChallenge = challenge; String imageUrl = ChanUrls.getCaptchaImageUrl(challenge); - + NetworkImageView captchaImage = new NetworkImageView(getActivity()); captchaImage.setImageUrl(imageUrl, ChanApplication.getImageLoader()); captchaContainer.setView(captchaImage); - + gettingCaptcha = false; } } @@ -375,7 +384,7 @@ public class ReplyFragment extends DialogFragment { } })); } - + /** * Submit button clicked at page 1 */ @@ -383,9 +392,9 @@ public class ReplyFragment extends DialogFragment { submitButton.setEnabled(false); cancelButton.setEnabled(false); setClosable(false); - + responseContainer.setView(null); - + draft.name = nameView.getText().toString(); draft.email = emailView.getText().toString(); draft.subject = subjectView.getText().toString(); @@ -393,10 +402,10 @@ public class ReplyFragment extends DialogFragment { draft.captchaChallenge = captchaChallenge; draft.captchaResponse = captchaText.getText().toString(); draft.fileName = "image"; - + draft.resto = loadable.isBoardMode() ? -1 : loadable.no; draft.board = loadable.board; - + ChanApplication.getReplyManager().sendReply(draft, new ReplyManager.ReplyListener() { @Override public void onResponse(ReplyResponse response) { @@ -404,16 +413,19 @@ public class ReplyFragment extends DialogFragment { } }); } - + /** * Got response about or reply from ReplyManager + * * @param response */ - private void handleSubmitResponse(ReplyResponse response) { - if (getActivity() == null) return; - + private void handleSubmitResponse(ReplyResponse response) { + if (getActivity() == null) + return; + if (response.isNetworkError || response.isUserError) { - int resId = response.isCaptchaError ? R.string.reply_error_captcha : (response.isFileError ? R.string.reply_error_file : R.string.reply_error); + int resId = response.isCaptchaError ? R.string.reply_error_captcha + : (response.isFileError ? R.string.reply_error_file : R.string.reply_error); Toast.makeText(getActivity(), resId, Toast.LENGTH_LONG).show(); submitButton.setEnabled(true); cancelButton.setEnabled(true); @@ -424,26 +436,21 @@ public class ReplyFragment extends DialogFragment { } else if (response.isSuccessful) { shouldSaveDraft = false; Toast.makeText(getActivity(), R.string.reply_success, Toast.LENGTH_SHORT).show(); -// threadFragment.reload(); // won't work: it takes 4chan a variable time to process the reply + // threadFragment.reload(); // won't work: it takes 4chan a variable time to process the reply closeReply(); } else { if (isVisible()) { cancelButton.setEnabled(true); setClosable(true); - + WebView webView = new WebView(getActivity()); WebSettings settings = webView.getSettings(); settings.setSupportZoom(true); - + webView.loadData(response.responseData, "text/html", null); - + responseContainer.setView(webView); } } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/fragment/SettingsFragment.java b/Chan/src/org/floens/chan/ui/fragment/SettingsFragment.java index 4c652a14..5fc75e54 100644 --- a/Chan/src/org/floens/chan/ui/fragment/SettingsFragment.java +++ b/Chan/src/org/floens/chan/ui/fragment/SettingsFragment.java @@ -48,8 +48,8 @@ public class SettingsFragment extends PreferenceFragment { ChanPreferences.setDeveloper(enabled); updateDeveloperPreference(); - Toast.makeText(getActivity(), - (enabled ? "Enabled " : "Disabled ") + "developer options", Toast.LENGTH_LONG).show(); + Toast.makeText(getActivity(), (enabled ? "Enabled " : "Disabled ") + "developer options", + Toast.LENGTH_LONG).show(); } return true; @@ -78,7 +78,8 @@ public class SettingsFragment extends PreferenceFragment { final Preference watchPreference = findPreference("watch_settings"); if (watchPreference != null) { - watchPreference.setSummary(ChanPreferences.getWatchEnabled() ? R.string.watch_summary_enabled : R.string.watch_summary_disabled); + watchPreference.setSummary(ChanPreferences.getWatchEnabled() ? R.string.watch_summary_enabled + : R.string.watch_summary_disabled); } } diff --git a/Chan/src/org/floens/chan/ui/fragment/ThreadFragment.java b/Chan/src/org/floens/chan/ui/fragment/ThreadFragment.java index 992ed912..bf0c1ac3 100644 --- a/Chan/src/org/floens/chan/ui/fragment/ThreadFragment.java +++ b/Chan/src/org/floens/chan/ui/fragment/ThreadFragment.java @@ -34,114 +34,116 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana private BaseActivity baseActivity; private ThreadManager threadManager; private Loadable loadable; - + private PostAdapter postAdapter; private LoadView container; private ListView listView; - + public static ThreadFragment newInstance(BaseActivity activity) { ThreadFragment fragment = new ThreadFragment(); fragment.baseActivity = activity; fragment.threadManager = new ThreadManager(activity, fragment); - + return fragment; } - + public void bindLoadable(Loadable l) { if (loadable != null) { threadManager.unbindLoader(); } - + setEmpty(); - + loadable = l; threadManager.bindLoader(loadable); } - + public void requestData() { threadManager.requestData(); } - + private void setEmpty() { postAdapter = null; - + if (container != null) { container.setView(null); } - + if (listView != null) { listView.setOnScrollListener(null); listView = null; } } - + public void reload() { setEmpty(); - + threadManager.requestData(); } - + public void openReply() { if (threadManager.hasLoader()) { threadManager.openReply(true); } } - + public boolean hasLoader() { return threadManager.hasLoader(); } - + @Override public void onDestroy() { super.onDestroy(); - + if (threadManager != null) { threadManager.onDestroy(); } } - + @Override public void onStart() { super.onStart(); - + if (threadManager != null) { threadManager.onStart(); } } - + @Override public void onStop() { super.onStop(); - + if (threadManager != null) { threadManager.onStop(); } } - + @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { container = new LoadView(inflater.getContext()); return container; } - + @Override public void onThreadLoaded(List posts, boolean append) { if (postAdapter == null) { listView = new ListView(baseActivity); - + postAdapter = new PostAdapter(baseActivity, threadManager, listView); - + listView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); listView.setAdapter(postAdapter); listView.setSelectionFromTop(loadable.listViewIndex, loadable.listViewTop); - + if (threadManager.getLoadable().isThreadMode()) { listView.setOnScrollListener(new OnScrollListener() { @Override - public void onScrollStateChanged(AbsListView view, int scrollState) {} - + public void onScrollStateChanged(AbsListView view, int scrollState) { + } + @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, + int totalItemCount) { if (loadable != null) { loadable.listViewIndex = view.getFirstVisiblePosition(); View v = view.getChildAt(0); @@ -150,19 +152,19 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana } }); } - + if (container != null) { container.setView(listView); } } - + if (append) { postAdapter.appendList(posts); } else { postAdapter.setList(posts); } } - + @Override public void onThreadLoadError(VolleyError error) { if (error instanceof EndOfLineException) { @@ -173,15 +175,16 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana } } } - + /** * Returns an TextView containing the appropriate error message + * * @param error * @return */ public TextView getLoadErrorTextView(VolleyError error) { String errorMessage = ""; - + if ((error instanceof NoConnectionError) || (error instanceof NetworkError)) { errorMessage = getActivity().getString(R.string.thread_load_failed_network); } else if (error instanceof ServerError) { @@ -189,26 +192,26 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana } else { errorMessage = getActivity().getString(R.string.thread_load_failed_parsing); } - + TextView view = new TextView(getActivity()); view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); view.setText(errorMessage); view.setTextSize(24f); view.setGravity(Gravity.CENTER); - + return view; } - + @Override public void onOPClicked(Post post) { baseActivity.onOPClicked(post); } - + @Override public void onThumbnailClicked(Post source) { if (postAdapter != null) { ImageViewActivity.setAdapter(postAdapter, source.no); - + Intent intent = new Intent(baseActivity, ImageViewActivity.class); baseActivity.startActivity(intent); baseActivity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out); @@ -222,8 +225,3 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/view/DynamicListView.java b/Chan/src/org/floens/chan/ui/view/DynamicListView.java index 07558ad9..6fec0a17 100644 --- a/Chan/src/org/floens/chan/ui/view/DynamicListView.java +++ b/Chan/src/org/floens/chan/ui/view/DynamicListView.java @@ -45,21 +45,22 @@ import android.widget.ListView; /** * The dynamic listview is an extension of listview that supports cell dragging * and swapping. - * - * This layout is in charge of positioning the hover cell in the correct location - * on the screen in response to user touch events. It uses the position of the - * hover cell to determine when two cells should be swapped. If two cells should - * be swapped, all the corresponding data set and layout changes are handled here. - * + * + * This layout is in charge of positioning the hover cell in the correct + * location on the screen in response to user touch events. It uses the position + * of the hover cell to determine when two cells should be swapped. If two cells + * should be swapped, all the corresponding data set and layout changes are + * handled here. + * * If no cell is selected, all the touch events are passed down to the listview - * and behave normally. If one of the items in the listview experiences a - * long press event, the contents of its current visible state are captured as - * a bitmap and its visibility is set to INVISIBLE. A hover cell is then created and - * added to this layout as an overlaying BitmapDrawable above the listview. Once the - * hover cell is translated some distance to signify an item swap, a data set change - * accompanied by animation takes place. When the user releases the hover cell, - * it animates into its corresponding position in the listview. - * + * and behave normally. If one of the items in the listview experiences a long + * press event, the contents of its current visible state are captured as a + * bitmap and its visibility is set to INVISIBLE. A hover cell is then created + * and added to this layout as an overlaying BitmapDrawable above the listview. + * Once the hover cell is translated some distance to signify an item swap, a + * data set change accompanied by animation takes place. When the user releases + * the hover cell, it animates into its corresponding position in the listview. + * * When the hover cell is either above or below the bounds of the listview, this * listview also scrolls on its own so as to reveal additional content. */ @@ -116,34 +117,33 @@ public class DynamicListView extends ListView { setOnItemLongClickListener(mOnItemLongClickListener); setOnScrollListener(mScrollListener); DisplayMetrics metrics = context.getResources().getDisplayMetrics(); - mSmoothScrollAmountAtEdge = (int)(SMOOTH_SCROLL_AMOUNT_AT_EDGE / metrics.density); + mSmoothScrollAmountAtEdge = (int) (SMOOTH_SCROLL_AMOUNT_AT_EDGE / metrics.density); } /** * Listens for long clicks on any items in the listview. When a cell has * been selected, the hover cell is created and set up. */ - private final AdapterView.OnItemLongClickListener mOnItemLongClickListener = - new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView arg0, View arg1, int pos, long id) { - mTotalOffset = 0; + private final AdapterView.OnItemLongClickListener mOnItemLongClickListener = new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView arg0, View arg1, int pos, long id) { + mTotalOffset = 0; - int position = pointToPosition(mDownX, mDownY); - int itemNum = position - getFirstVisiblePosition(); + int position = pointToPosition(mDownX, mDownY); + int itemNum = position - getFirstVisiblePosition(); - View selectedView = getChildAt(itemNum); - mMobileItemId = getAdapter().getItemId(position); - mHoverCell = getAndAddHoverView(selectedView); - selectedView.setVisibility(INVISIBLE); + View selectedView = getChildAt(itemNum); + mMobileItemId = getAdapter().getItemId(position); + mHoverCell = getAndAddHoverView(selectedView); + selectedView.setVisibility(INVISIBLE); - mCellIsMobile = true; + mCellIsMobile = true; - updateNeighborViewsForID(mMobileItemId); + updateNeighborViewsForID(mMobileItemId); - return true; - } - }; + return true; + } + }; /** * Creates the hover cell with the appropriate bitmap and of appropriate @@ -190,7 +190,7 @@ public class DynamicListView extends ListView { /** Returns a bitmap showing a screenshot of the view passed in. */ private Bitmap getBitmapFromView(View v) { Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas (bitmap); + Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; } @@ -198,21 +198,21 @@ public class DynamicListView extends ListView { /** * Stores a reference to the views above and below the item currently * corresponding to the hover cell. It is important to note that if this - * item is either at the top or bottom of the list, mAboveItemId or mBelowItemId - * may be invalid. + * item is either at the top or bottom of the list, mAboveItemId or + * mBelowItemId may be invalid. */ private void updateNeighborViewsForID(long itemID) { int position = getPositionForID(itemID); - BoardEditAdapter adapter = ((BoardEditAdapter)getAdapter()); + BoardEditAdapter adapter = ((BoardEditAdapter) getAdapter()); mAboveItemId = adapter.getItemId(position - 1); mBelowItemId = adapter.getItemId(position + 1); } /** Retrieves the view in the list corresponding to itemID */ - public View getViewForID (long itemID) { + public View getViewForID(long itemID) { int firstVisiblePosition = getFirstVisiblePosition(); - BoardEditAdapter adapter = ((BoardEditAdapter)getAdapter()); - for(int i = 0; i < getChildCount(); i++) { + BoardEditAdapter adapter = ((BoardEditAdapter) getAdapter()); + for (int i = 0; i < getChildCount(); i++) { View v = getChildAt(i); int position = firstVisiblePosition + i; long id = adapter.getItemId(position); @@ -224,7 +224,7 @@ public class DynamicListView extends ListView { } /** Retrieves the position in the list corresponding to itemID */ - public int getPositionForID (long itemID) { + public int getPositionForID(long itemID) { View v = getViewForID(itemID); if (v == null) { return -1; @@ -234,9 +234,9 @@ public class DynamicListView extends ListView { } /** - * dispatchDraw gets invoked when all the child views are about to be drawn. - * By overriding this method, the hover cell (BitmapDrawable) can be drawn - * over the listview's items whenever the listview is redrawn. + * dispatchDraw gets invoked when all the child views are about to be drawn. + * By overriding this method, the hover cell (BitmapDrawable) can be drawn + * over the listview's items whenever the listview is redrawn. */ @Override protected void dispatchDraw(Canvas canvas) { @@ -247,58 +247,57 @@ public class DynamicListView extends ListView { } @Override - public boolean onTouchEvent (MotionEvent event) { + public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: - mDownX = (int)event.getX(); - mDownY = (int)event.getY(); - mActivePointerId = event.getPointerId(0); + case MotionEvent.ACTION_DOWN: + mDownX = (int) event.getX(); + mDownY = (int) event.getY(); + mActivePointerId = event.getPointerId(0); + break; + case MotionEvent.ACTION_MOVE: + if (mActivePointerId == INVALID_POINTER_ID) { break; - case MotionEvent.ACTION_MOVE: - if (mActivePointerId == INVALID_POINTER_ID) { - break; - } + } - int pointerIndex = event.findPointerIndex(mActivePointerId); + int pointerIndex = event.findPointerIndex(mActivePointerId); - mLastEventY = (int) event.getY(pointerIndex); - int deltaY = mLastEventY - mDownY; + mLastEventY = (int) event.getY(pointerIndex); + int deltaY = mLastEventY - mDownY; - if (mCellIsMobile) { - mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left, - mHoverCellOriginalBounds.top + deltaY + mTotalOffset); - mHoverCell.setBounds(mHoverCellCurrentBounds); - invalidate(); + if (mCellIsMobile) { + mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left, mHoverCellOriginalBounds.top + deltaY + + mTotalOffset); + mHoverCell.setBounds(mHoverCellCurrentBounds); + invalidate(); - handleCellSwitch(); + handleCellSwitch(); - mIsMobileScrolling = false; - handleMobileCellScroll(); + mIsMobileScrolling = false; + handleMobileCellScroll(); - return false; - } - break; - case MotionEvent.ACTION_UP: + return false; + } + break; + case MotionEvent.ACTION_UP: + touchEventsEnded(); + break; + case MotionEvent.ACTION_CANCEL: + touchEventsCancelled(); + break; + case MotionEvent.ACTION_POINTER_UP: + /* If a multitouch event took place and the original touch dictating + * the movement of the hover cell has ended, then the dragging event + * ends and the hover cell is animated to its corresponding position + * in the listview. */ + pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; + final int pointerId = event.getPointerId(pointerIndex); + if (pointerId == mActivePointerId) { touchEventsEnded(); - break; - case MotionEvent.ACTION_CANCEL: - touchEventsCancelled(); - break; - case MotionEvent.ACTION_POINTER_UP: - /* If a multitouch event took place and the original touch dictating - * the movement of the hover cell has ended, then the dragging event - * ends and the hover cell is animated to its corresponding position - * in the listview. */ - pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> - MotionEvent.ACTION_POINTER_INDEX_SHIFT; - final int pointerId = event.getPointerId(pointerIndex); - if (pointerId == mActivePointerId) { - touchEventsEnded(); - } - break; - default: - break; + } + break; + default: + break; } return super.onTouchEvent(event); @@ -307,11 +306,11 @@ public class DynamicListView extends ListView { /** * This method determines whether the hover cell has been shifted far enough * to invoke a cell swap. If so, then the respective cell swap candidate is - * determined and the data set is changed. Upon posting a notification of the - * data set change, a layout is invoked to place the cells in the right place. - * Using a ViewTreeObserver and a corresponding OnPreDrawListener, we can - * offset the cell being swapped to where it previously was and then animate it to - * its new position. + * determined and the data set is changed. Upon posting a notification of + * the data set change, a layout is invoked to place the cells in the right + * place. Using a ViewTreeObserver and a corresponding OnPreDrawListener, we + * can offset the cell being swapped to where it previously was and then + * animate it to its new position. */ private void handleCellSwitch() { final int deltaY = mLastEventY - mDownY; @@ -363,8 +362,7 @@ public class DynamicListView extends ListView { switchView.setTranslationY(delta); - ObjectAnimator animator = ObjectAnimator.ofFloat(switchView, - View.TRANSLATION_Y, 0); + ObjectAnimator animator = ObjectAnimator.ofFloat(switchView, View.TRANSLATION_Y, 0); animator.setDuration(MOVE_DURATION); animator.start(); @@ -380,14 +378,13 @@ public class DynamicListView extends ListView { arrayList.set(indexTwo, temp); } - /** * Resets all the appropriate fields to a default state while also animating * the hover cell back to its correct location. */ - private void touchEventsEnded () { + private void touchEventsEnded() { final View mobileView = getViewForID(mMobileItemId); - if (mCellIsMobile|| mIsWaitingForScrollFinish) { + if (mCellIsMobile || mIsWaitingForScrollFinish) { mCellIsMobile = false; mIsWaitingForScrollFinish = false; mIsMobileScrolling = false; @@ -403,8 +400,8 @@ public class DynamicListView extends ListView { mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left, mobileView.getTop()); - ObjectAnimator hoverViewAnimator = ObjectAnimator.ofObject(mHoverCell, "bounds", - sBoundEvaluator, mHoverCellCurrentBounds); + ObjectAnimator hoverViewAnimator = ObjectAnimator.ofObject(mHoverCell, "bounds", sBoundEvaluator, + mHoverCellCurrentBounds); hoverViewAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { @@ -437,7 +434,7 @@ public class DynamicListView extends ListView { /** * Resets all the appropriate fields to a default state. */ - private void touchEventsCancelled () { + private void touchEventsCancelled() { View mobileView = getViewForID(mMobileItemId); if (mCellIsMobile) { mAboveItemId = INVALID_ID; @@ -460,28 +457,27 @@ public class DynamicListView extends ListView { private final static TypeEvaluator sBoundEvaluator = new TypeEvaluator() { @Override public Rect evaluate(float fraction, Rect startValue, Rect endValue) { - return new Rect(interpolate(startValue.left, endValue.left, fraction), - interpolate(startValue.top, endValue.top, fraction), - interpolate(startValue.right, endValue.right, fraction), - interpolate(startValue.bottom, endValue.bottom, fraction)); + return new Rect(interpolate(startValue.left, endValue.left, fraction), interpolate(startValue.top, + endValue.top, fraction), interpolate(startValue.right, endValue.right, fraction), interpolate( + startValue.bottom, endValue.bottom, fraction)); } public int interpolate(int start, int end, float fraction) { - return (int)(start + fraction * (end - start)); + return (int) (start + fraction * (end - start)); } }; /** - * Determines whether this listview is in a scrolling state invoked - * by the fact that the hover cell is out of the bounds of the listview; + * Determines whether this listview is in a scrolling state invoked by the + * fact that the hover cell is out of the bounds of the listview; */ private void handleMobileCellScroll() { mIsMobileScrolling = handleMobileCellScroll(mHoverCellCurrentBounds); } /** - * This method is in charge of determining if the hover cell is above - * or below the bounds of the listview. If so, the listview does an appropriate + * This method is in charge of determining if the hover cell is above or + * below the bounds of the listview. If so, the listview does an appropriate * upward or downward smooth scroll so as to reveal new items. */ public boolean handleMobileCellScroll(Rect r) { @@ -510,13 +506,14 @@ public class DynamicListView extends ListView { } /** - * This scroll listener is added to the listview in order to handle cell swapping - * when the cell is either at the top or bottom edge of the listview. If the hover - * cell is at either edge of the listview, the listview will begin scrolling. As - * scrolling takes place, the listview continuously checks if new cells became visible - * and determines whether they are potential candidates for a cell swap. + * This scroll listener is added to the listview in order to handle cell + * swapping when the cell is either at the top or bottom edge of the + * listview. If the hover cell is at either edge of the listview, the + * listview will begin scrolling. As scrolling takes place, the listview + * continuously checks if new cells became visible and determines whether + * they are potential candidates for a cell swap. */ - private final AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener () { + private final AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener() { private int mPreviousFirstVisibleItem = -1; private int mPreviousVisibleItemCount = -1; @@ -525,8 +522,7 @@ public class DynamicListView extends ListView { private int mCurrentScrollState; @Override - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, - int totalItemCount) { + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { mCurrentFirstVisibleItem = firstVisibleItem; mCurrentVisibleItemCount = visibleItemCount; @@ -550,12 +546,12 @@ public class DynamicListView extends ListView { } /** - * This method is in charge of invoking 1 of 2 actions. Firstly, if the listview - * is in a state of scrolling invoked by the hover cell being outside the bounds - * of the listview, then this scrolling event is continued. Secondly, if the hover - * cell has already been released, this invokes the animation for the hover cell - * to return to its correct position after the listview has entered an idle scroll - * state. + * This method is in charge of invoking 1 of 2 actions. Firstly, if the + * listview is in a state of scrolling invoked by the hover cell being + * outside the bounds of the listview, then this scrolling event is + * continued. Secondly, if the hover cell has already been released, + * this invokes the animation for the hover cell to return to its + * correct position after the listview has entered an idle scroll state. */ private void isScrollCompleted() { if (mCurrentVisibleItemCount > 0 && mCurrentScrollState == SCROLL_STATE_IDLE) { @@ -568,8 +564,9 @@ public class DynamicListView extends ListView { } /** - * Determines if the listview scrolled up enough to reveal a new cell at the - * top of the list. If so, then the appropriate parameters are updated. + * Determines if the listview scrolled up enough to reveal a new cell at + * the top of the list. If so, then the appropriate parameters are + * updated. */ public void checkAndHandleFirstVisibleCellChange() { if (mCurrentFirstVisibleItem != mPreviousFirstVisibleItem) { @@ -581,8 +578,9 @@ public class DynamicListView extends ListView { } /** - * Determines if the listview scrolled down enough to reveal a new cell at the - * bottom of the list. If so, then the appropriate parameters are updated. + * Determines if the listview scrolled down enough to reveal a new cell + * at the bottom of the list. If so, then the appropriate parameters are + * updated. */ public void checkAndHandleLastVisibleCellChange() { int currentLastVisibleItem = mCurrentFirstVisibleItem + mCurrentVisibleItemCount; diff --git a/Chan/src/org/floens/chan/ui/view/GIFView.java b/Chan/src/org/floens/chan/ui/view/GIFView.java index e316b0ad..cd8601c2 100644 --- a/Chan/src/org/floens/chan/ui/view/GIFView.java +++ b/Chan/src/org/floens/chan/ui/view/GIFView.java @@ -12,34 +12,34 @@ import android.view.View; public class GIFView extends View { private Movie movie; private long movieStart; - + public GIFView(Context activity) { super(activity); init(); } - + public GIFView(Context activity, AttributeSet attbs) { super(activity, attbs); init(); } - + public GIFView(Context activity, AttributeSet attbs, int style) { super(activity, attbs, style); init(); } - + private void init() { Paint paint = new Paint(); paint.setAntiAlias(true); setLayerType(LAYER_TYPE_SOFTWARE, paint); } - + public boolean setData(byte[] array) { Movie movie = Movie.decodeByteArray(array, 0, array.length); - + return onMovieLoaded(movie); } - + private boolean onMovieLoaded(Movie movie) { if (movie != null) { this.movie = movie; @@ -49,53 +49,48 @@ public class GIFView extends View { return false; } } - + @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.TRANSPARENT); - + super.onDraw(canvas); - + long now = SystemClock.uptimeMillis(); - + if (movieStart == 0) { // first time movieStart = now; } - + if (movie != null) { int dur = movie.duration(); - + if (dur == 0) { dur = 1000; } - - int relTime = (int)((now - movieStart) % dur); + + int relTime = (int) ((now - movieStart) % dur); movie.setTime(relTime); - + canvas.save(); - - float width = (float)getWidth() / (float)movie.width(); - float height = (float)getHeight() / (float)movie.height(); - + + float width = (float) getWidth() / (float) movie.width(); + float height = (float) getHeight() / (float) movie.height(); + float scale = width > height ? height : width; - + int widthPixels = (int) (movie.width() * scale); int heightPixels = (int) (movie.height() * scale); - + canvas.translate((getWidth() - widthPixels) / 2, (getHeight() - heightPixels) / 2); - + canvas.scale(scale, scale); - + movie.draw(canvas, 0, 0); - + canvas.restore(); - + invalidate(); } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/view/HackyViewPager.java b/Chan/src/org/floens/chan/ui/view/HackyViewPager.java index 5e26a408..99213968 100644 --- a/Chan/src/org/floens/chan/ui/view/HackyViewPager.java +++ b/Chan/src/org/floens/chan/ui/view/HackyViewPager.java @@ -15,7 +15,7 @@ import android.view.MotionEvent; * * There's not much I can do in my code for now, but we can mask the result by * just catching the problem and ignoring it. - * + * * @author Chris Banes */ public class HackyViewPager extends ViewPager { diff --git a/Chan/src/org/floens/chan/ui/view/NetworkPhotoView.java b/Chan/src/org/floens/chan/ui/view/NetworkPhotoView.java index 95dca7dc..ba8fe472 100644 --- a/Chan/src/org/floens/chan/ui/view/NetworkPhotoView.java +++ b/Chan/src/org/floens/chan/ui/view/NetworkPhotoView.java @@ -12,9 +12,8 @@ import android.widget.Toast; import com.android.volley.VolleyError; /** - * Extends NetworkImageView. - * Attaches a PhotoViewAttacher when setBitmap is called. - * Sets the progressBar to false when a bitmap gets set. + * Extends NetworkImageView. Attaches a PhotoViewAttacher when setBitmap is + * called. Sets the progressBar to false when a bitmap gets set. */ public class NetworkPhotoView extends CustomNetworkImageView { private PhotoViewAttacher attacher; @@ -70,8 +69,3 @@ public class NetworkPhotoView extends CustomNetworkImageView { } } } - - - - - diff --git a/Chan/src/org/floens/chan/ui/view/PostView.java b/Chan/src/org/floens/chan/ui/view/PostView.java index c0730766..003290aa 100644 --- a/Chan/src/org/floens/chan/ui/view/PostView.java +++ b/Chan/src/org/floens/chan/ui/view/PostView.java @@ -216,7 +216,7 @@ public class PostView extends LinearLayout implements View.OnClickListener, View } else { full.setBackgroundColor(0x00000000); } - + if (manager.isPostLastSeen(post)) { lastSeen.setVisibility(View.VISIBLE); } else { diff --git a/Chan/src/org/floens/chan/ui/view/ThreadWatchCounterView.java b/Chan/src/org/floens/chan/ui/view/ThreadWatchCounterView.java index e283840b..c892d181 100644 --- a/Chan/src/org/floens/chan/ui/view/ThreadWatchCounterView.java +++ b/Chan/src/org/floens/chan/ui/view/ThreadWatchCounterView.java @@ -15,25 +15,25 @@ public class ThreadWatchCounterView extends TextView implements View.OnClickList private boolean detached = false; private ThreadManager tm; private BaseAdapter ad; - + public ThreadWatchCounterView(Context activity) { super(activity); } - + public ThreadWatchCounterView(Context activity, AttributeSet attbs) { super(activity, attbs); } - + public ThreadWatchCounterView(Context activity, AttributeSet attbs, int style) { super(activity, attbs, style); } - + public void init(final ThreadManager threadManager, final ListView listView, final BaseAdapter adapter) { tm = threadManager; ad = adapter; - + updateCounterText(threadManager); - + new Handler().postDelayed(new Runnable() { @Override public void run() { @@ -42,35 +42,36 @@ public class ThreadWatchCounterView extends TextView implements View.OnClickList } } }, 1000); - + setOnClickListener(this); } - + @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - + setOnClickListener(null); - + detached = true; } - + @Override public void onClick(View v) { Loader loader = tm.getLoader(); if (loader != null) { loader.requestMoreDataAndResetTimer(); } - + ad.notifyDataSetChanged(); } - + private void updateCounterText(ThreadManager threadManager) { Loader loader = tm.getLoader(); - if (loader == null) return; - + if (loader == null) + return; + int time = Math.round(loader.getTimeUntilLoadMore() / 1000f); - + if (time <= 0) { setText("Loading"); } else { @@ -78,7 +79,3 @@ public class ThreadWatchCounterView extends TextView implements View.OnClickList } } } - - - - diff --git a/Chan/src/org/floens/chan/utils/IOUtils.java b/Chan/src/org/floens/chan/utils/IOUtils.java index b2a9d077..bcd3621d 100644 --- a/Chan/src/org/floens/chan/utils/IOUtils.java +++ b/Chan/src/org/floens/chan/utils/IOUtils.java @@ -11,7 +11,7 @@ import java.io.Writer; public class IOUtils { public static String readString(InputStream is) { StringWriter sw = new StringWriter(); - + try { copy(new InputStreamReader(is), sw); is.close(); @@ -19,12 +19,13 @@ public class IOUtils { } catch (IOException e) { e.printStackTrace(); } - + return sw.toString(); } - + /** * Copies the inputstream to the outputstream and closes both streams. + * * @param is * @param os * @throws IOException @@ -35,11 +36,11 @@ public class IOUtils { while ((read = is.read(buffer)) != -1) { os.write(buffer, 0, read); } - + is.close(); os.close(); } - + public static void copy(Reader input, Writer output) throws IOException { char[] buffer = new char[4096]; int read = 0; diff --git a/Chan/src/org/floens/chan/utils/IconCache.java b/Chan/src/org/floens/chan/utils/IconCache.java index 3b19916a..1dcaa8cc 100644 --- a/Chan/src/org/floens/chan/utils/IconCache.java +++ b/Chan/src/org/floens/chan/utils/IconCache.java @@ -12,6 +12,7 @@ public class IconCache { /** * Load the icons in the cache. Lightweight icons only! Icons can be null! + * * @param context */ public static void createIcons(final Context context) { diff --git a/Chan/src/org/floens/chan/utils/ImageDecoder.java b/Chan/src/org/floens/chan/utils/ImageDecoder.java index 1a8b2725..e042a9a2 100644 --- a/Chan/src/org/floens/chan/utils/ImageDecoder.java +++ b/Chan/src/org/floens/chan/utils/ImageDecoder.java @@ -14,24 +14,25 @@ import android.graphics.BitmapFactory; */ public class ImageDecoder { public static Bitmap decodeFile(File file, int maxWidth, int maxHeight) { - if (!file.exists()) return null; - + if (!file.exists()) + return null; + FileInputStream fis; - + try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - + Bitmap bitmap = null; - + try { IOUtils.copy(fis, baos); - + bitmap = decode(baos.toByteArray(), maxWidth, maxHeight); } catch (IOException e) { e.printStackTrace(); @@ -45,14 +46,14 @@ public class ImageDecoder { e.printStackTrace(); } } - + return bitmap; } - + public static Bitmap decode(byte[] data, int maxWidth, int maxHeight) { BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); Bitmap bitmap = null; - + // If we have to resize this image, first get the natural bounds. decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); @@ -60,25 +61,19 @@ public class ImageDecoder { int actualHeight = decodeOptions.outHeight; // Then compute the dimensions we would ideally like to decode to. - int desiredWidth = getResizedDimension(maxWidth, maxHeight, - actualWidth, actualHeight); - int desiredHeight = getResizedDimension(maxHeight, maxWidth, - actualHeight, actualWidth); + int desiredWidth = getResizedDimension(maxWidth, maxHeight, actualWidth, actualHeight); + int desiredHeight = getResizedDimension(maxHeight, maxWidth, actualHeight, actualWidth); // Decode to the nearest power of two scaling factor. decodeOptions.inJustDecodeBounds = false; - + // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED; - decodeOptions.inSampleSize = - findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); - Bitmap tempBitmap = - BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); + decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); + Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); // If necessary, scale down to the maximal acceptable size. - if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || - tempBitmap.getHeight() > desiredHeight)) { - bitmap = Bitmap.createScaledBitmap(tempBitmap, - desiredWidth, desiredHeight, true); + if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) { + bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; @@ -86,7 +81,7 @@ public class ImageDecoder { return bitmap; } - + private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, int actualSecondary) { // If no dominant value at all, just return the actual. if (maxPrimary == 0 && maxSecondary == 0) { @@ -110,7 +105,7 @@ public class ImageDecoder { } return resized; } - + private static int findBestSampleSize(int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) { double wr = (double) actualWidth / desiredWidth; double hr = (double) actualHeight / desiredHeight; diff --git a/Chan/src/org/floens/chan/utils/ImageSaver.java b/Chan/src/org/floens/chan/utils/ImageSaver.java index 00b76c19..e7046dab 100644 --- a/Chan/src/org/floens/chan/utils/ImageSaver.java +++ b/Chan/src/org/floens/chan/utils/ImageSaver.java @@ -20,7 +20,7 @@ import com.android.volley.VolleyError; public class ImageSaver { private static final String TAG = "ImageSaver"; - + public static void save(final Context context, String imageUrl, final String name, final String extension) { ByteArrayRequest request = new ByteArrayRequest(imageUrl, new Response.Listener() { @Override @@ -33,63 +33,61 @@ public class ImageSaver { Toast.makeText(context, R.string.image_preview_failed, Toast.LENGTH_LONG).show(); } }); - + ChanApplication.getVolleyRequestQueue().add(request); } - + private static void storeImage(final Context context, byte[] data, String name, String extension) { String errorReason = null; - + try { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { errorReason = context.getString(R.string.image_save_not_mounted); throw new IOException(errorReason); } - - File path = new File(Environment.getExternalStorageDirectory() + File.separator + ChanPreferences.getImageSaveDirectory()); - + + File path = new File(Environment.getExternalStorageDirectory() + File.separator + + ChanPreferences.getImageSaveDirectory()); + if (!path.exists()) { if (!path.mkdirs()) { errorReason = context.getString(R.string.image_save_directory_error); throw new IOException(errorReason); } } - + File file = new File(path, name + "." + extension); int nextFileNameNumber = 0; String newName; - while(file.exists()) { + while (file.exists()) { newName = name + "_" + Integer.toString(nextFileNameNumber) + "." + extension; file = new File(path, newName); nextFileNameNumber++; } - - Logger.i(TAG, "Saving image to: " + file.getPath()); - + + Logger.i(TAG, "Saving image to: " + file.getPath()); + FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(data); outputStream.close(); - - MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, new MediaScannerConnection.OnScanCompletedListener() { - @Override - public void onScanCompleted(String path, Uri uri) { - Logger.i(TAG, "Media scan succeeded: " + uri); - } - }); - + + MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, + new MediaScannerConnection.OnScanCompletedListener() { + @Override + public void onScanCompleted(String path, Uri uri) { + Logger.i(TAG, "Media scan succeeded: " + uri); + } + }); + String message = context.getResources().getString(R.string.image_save_succeeded) + " " + file.getName(); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); - - if (errorReason == null) errorReason = context.getString(R.string.image_save_failed); - + + if (errorReason == null) + errorReason = context.getString(R.string.image_save_failed); + Toast.makeText(context, errorReason, Toast.LENGTH_LONG).show(); } } } - - - - - diff --git a/Chan/src/org/floens/chan/utils/Logger.java b/Chan/src/org/floens/chan/utils/Logger.java index e52898e5..c874d68f 100644 --- a/Chan/src/org/floens/chan/utils/Logger.java +++ b/Chan/src/org/floens/chan/utils/Logger.java @@ -7,47 +7,47 @@ import android.util.Log; public class Logger { private static final String TAG = "Chan"; private static final String TAG_SPACER = " | "; - + public static void v(String tag, String message) { Log.v(TAG + TAG_SPACER + tag, message); } - + public static void v(String tag, String message, Throwable throwable) { Log.v(TAG + TAG_SPACER + tag, message, throwable); } - + public static void d(String tag, String message) { if (ChanApplication.DEVELOPER_MODE) { Log.d(TAG + TAG_SPACER + tag, message); } } - + public static void d(String tag, String message, Throwable throwable) { if (ChanApplication.DEVELOPER_MODE) { Log.d(TAG + TAG_SPACER + tag, message, throwable); } } - + public static void i(String tag, String message) { Log.i(TAG + TAG_SPACER + tag, message); } - + public static void i(String tag, String message, Throwable throwable) { Log.i(TAG + TAG_SPACER + tag, message, throwable); } - + public static void w(String tag, String message) { Log.w(TAG + TAG_SPACER + tag, message); } - + public static void w(String tag, String message, Throwable throwable) { Log.w(TAG + TAG_SPACER + tag, message, throwable); } - + public static void e(String tag, String message) { Log.e(TAG + TAG_SPACER + tag, message); } - + public static void e(String tag, String message, Throwable throwable) { Log.e(TAG + TAG_SPACER + tag, message, throwable); } @@ -55,21 +55,20 @@ public class Logger { public static void wtf(String tag, String message) { Log.wtf(TAG + TAG_SPACER + tag, message); } - + public static void wtf(String tag, String message, Throwable throwable) { Log.wtf(TAG + TAG_SPACER + tag, message, throwable); } - + public static void test(String message) { if (ChanApplication.DEVELOPER_MODE) { Log.i(TAG + TAG_SPACER + "test", message); } } - + public static void test(String message, Throwable throwable) { if (ChanApplication.DEVELOPER_MODE) { Log.i(TAG + TAG_SPACER + "test", message, throwable); } } } - diff --git a/Chan/src/org/floens/chan/utils/Utils.java b/Chan/src/org/floens/chan/utils/Utils.java index 2999a142..a5f59bbc 100644 --- a/Chan/src/org/floens/chan/utils/Utils.java +++ b/Chan/src/org/floens/chan/utils/Utils.java @@ -13,23 +13,29 @@ import android.view.ViewGroup; public class Utils { private static DisplayMetrics displayMetrics; - - public final static ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - public final static ViewGroup.LayoutParams WRAP_PARAMS = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); - public final static ViewGroup.LayoutParams MATCH_WRAP_PARAMS = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - public final static ViewGroup.LayoutParams WRAP_MATCH_PARAMS = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); - + + public final static ViewGroup.LayoutParams MATCH_PARAMS = new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + public final static ViewGroup.LayoutParams WRAP_PARAMS = new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + public final static ViewGroup.LayoutParams MATCH_WRAP_PARAMS = new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + public final static ViewGroup.LayoutParams WRAP_MATCH_PARAMS = new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); + public static int dp(float dp) { -// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); + // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); if (displayMetrics == null) { displayMetrics = ChanApplication.getInstance().getResources().getDisplayMetrics(); } - + return (int) (dp * displayMetrics.density); } /** - * Sets the android.R.attr.selectableItemBackground as background drawable on the view. + * Sets the android.R.attr.selectableItemBackground as background drawable + * on the view. + * * @param view */ @SuppressWarnings("deprecation") @@ -39,8 +45,7 @@ public class Utils { } public static Drawable getSelectableBackgroundDrawable(Context context) { - TypedArray arr = context.obtainStyledAttributes( - new int[] {android.R.attr.selectableItemBackground}); + TypedArray arr = context.obtainStyledAttributes(new int[] { android.R.attr.selectableItemBackground }); Drawable drawable = arr.getDrawable(0); @@ -50,8 +55,9 @@ public class Utils { } /** - * Causes the runnable to be added to the message queue. - * The runnable will be run on the ui thread. + * Causes the runnable to be added to the message queue. The runnable will + * be run on the ui thread. + * * @param runnable */ public static void runOnUiThread(Runnable runnable) {