commit faf8bb20a6ec0b2069211998842662b2d4f170b3 Author: Manan Habib Date: Thu Mar 16 00:13:56 2017 +0500 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..39fb081 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100755 index 0000000..96cc43e --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100755 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100755 index 0000000..42cdeac --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100755 index 0000000..5d19981 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100755 index 0000000..fed4a22 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100755 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100755 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100755 index 0000000..6fa4c20 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 25 + buildToolsVersion "25.0.0" + defaultConfig { + applicationId "com.example.manan.enhancedurdureader" + minSdkVersion 19 + targetSdkVersion 25 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(include: ['*.jar'], dir: 'libs') + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { + exclude group: 'com.android.support', module: 'support-annotations' + }) + compile 'com.android.support:appcompat-v7:25.0.0' + compile 'com.android.support:design:25.0.0' + testCompile 'junit:junit:4.12' + compile 'com.github.moondroid.coverflow:library:1.0' + compile 'com.github.bumptech.glide:glide:3.7.0' + compile 'com.squareup.picasso:picasso:2.5.2' + compile files('libs/epublib-core-latest.jar') + compile files('libs/slf4j-android-1.6.1-RC1.jar') +} diff --git a/app/libs/epublib-core-latest.jar b/app/libs/epublib-core-latest.jar new file mode 100755 index 0000000..6799a30 Binary files /dev/null and b/app/libs/epublib-core-latest.jar differ diff --git a/app/libs/slf4j-android-1.6.1-RC1.jar b/app/libs/slf4j-android-1.6.1-RC1.jar new file mode 100755 index 0000000..480348f Binary files /dev/null and b/app/libs/slf4j-android-1.6.1-RC1.jar differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100755 index 0000000..40b85a8 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /home/manan/Android/Sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/androidTest/java/com/example/manan/enhancedurdureader/ExampleInstrumentedTest.java b/app/src/androidTest/java/com/example/manan/enhancedurdureader/ExampleInstrumentedTest.java new file mode 100755 index 0000000..6e27806 --- /dev/null +++ b/app/src/androidTest/java/com/example/manan/enhancedurdureader/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.example.manan.enhancedurdureader; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumentation test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() throws Exception { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("com.example.manan.enhancedurdureader", appContext.getPackageName()); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100755 index 0000000..6ea2185 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/assets/fonts/MavenPro-Regular.ttf b/app/src/main/assets/fonts/MavenPro-Regular.ttf new file mode 100755 index 0000000..6442c2b Binary files /dev/null and b/app/src/main/assets/fonts/MavenPro-Regular.ttf differ diff --git a/app/src/main/assets/fonts/nastaleeq.ttf b/app/src/main/assets/fonts/nastaleeq.ttf new file mode 100755 index 0000000..1c16ec1 Binary files /dev/null and b/app/src/main/assets/fonts/nastaleeq.ttf differ diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticlePublishActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticlePublishActivity.java new file mode 100644 index 0000000..d7f484c --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticlePublishActivity.java @@ -0,0 +1,132 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.content.Intent; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.Gravity; + +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.AdapterView; +import android.widget.TextSwitcher; +import android.widget.TextView; +import android.widget.ViewSwitcher; + +import com.example.manan.enhancedurdureader.Adapters.ArticlePublishAdapter; +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + + +import java.util.ArrayList; + +import it.moondroid.coverflow.components.ui.containers.FeatureCoverFlow; + +public class ArticlePublishActivity extends AppCompatActivity { + + private FeatureCoverFlow mCoverFlow; + private ArticlePublishAdapter mAdapter; + private ArrayList mData = new ArrayList<>(0); + private TextSwitcher mTitle; + LocalStorage db; + Intent magzineSelectorIntent; + Integer articleId; + + private void intentInformation() { + + magzineSelectorIntent = getIntent(); + articleId = magzineSelectorIntent.getIntExtra("articleId", -1); + + + } + private void updateDataList(){ + + db = new LocalStorage(this, null, null, 1); + mData = new ArrayList<>(); + for(Magazine o:db.getAllMagzines()) { + if(o != null) { + if(o.get_id() != 1 && o.get_id() != 2) + mData.add(o) ; + + } + + } + } + + private void setMagzineAdapter(){ + + mAdapter = new ArticlePublishAdapter(this); + mAdapter.setData(mData); + mCoverFlow = (FeatureCoverFlow) findViewById(R.id.publish_magazine_coverflow); + mCoverFlow.setAdapter(mAdapter); + + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_article_publish); + + intentInformation(); + updateDataList(); + + mTitle = (TextSwitcher) findViewById(R.id.publish_magazine_title_switcher); + mTitle.setFactory(new ViewSwitcher.ViewFactory() { + @Override + public View makeView() { + TextView textView = new TextView(getApplicationContext()); + textView.setGravity(Gravity.CENTER); + textView.setTextAppearance(getApplicationContext(),android.R.style.TextAppearance_Large); + + return textView; + } + }); + Animation in = AnimationUtils.loadAnimation(this, R.anim.slide_in_top); + Animation out = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom); + mTitle.setInAnimation(in); + mTitle.setOutAnimation(out); + + setMagzineAdapter(); + + mCoverFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + + Article article = new Article(); + article.set_id(articleId); + int actualPosition = position%mData.size(); + article.setMagzineId(mData.get(actualPosition).get_id()); + + db.updateArticle(article); + + finish(); + } + }); + + + + mCoverFlow.setOnScrollPositionListener(new FeatureCoverFlow.OnScrollPositionListener() { + @Override + public void onScrolledToPosition(int position) { + mTitle.setText(mData.get(position%mData.size()).getTitleResId()); + } + + @Override + public void onScrolling() { + mTitle.setText(""); + } + }); + + } + + + @Override + protected void onResume() { + super.onResume(); + updateDataList(); + setMagzineAdapter(); + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticleReadingActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticleReadingActivity.java new file mode 100644 index 0000000..d475eeb --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/ArticleReadingActivity.java @@ -0,0 +1,179 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.support.annotation.Nullable; +import android.support.design.widget.FloatingActionButton; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.text.method.ScrollingMovementMethod; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.ArticleVote; +import com.example.manan.enhancedurdureader.CustomViews.NastaleeqTextView; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +public class ArticleReadingActivity extends AppCompatActivity { + + Integer articleId; + NastaleeqTextView title; + NastaleeqTextView body; + LocalStorage db; + Article article; + ImageView upvotes; + ImageView downvotes; + TextView totalUpvotes; + TextView totalDownvotes; + Intent articleIntent; + + Integer currentUpvotes; + Integer currentDownvotes; + + SharedPreferences userProfileStorage; + public static final String USER_PROFILE_STORAGE = "UserProfileStorage" ; + + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_article_reading); + + userProfileStorage = getSharedPreferences(USER_PROFILE_STORAGE, Context.MODE_PRIVATE); + + articleIntent = getIntent(); + articleId = articleIntent.getIntExtra("articleId", -1); + + updateValues(); + + upvotes = (ImageView)findViewById(R.id.upvote); + totalUpvotes = (TextView) findViewById(R.id.total_upvotes); + currentUpvotes = db.getAllUpvotes(article.get_id(), article.getMagzineId()); + totalUpvotes.setText(currentUpvotes.toString()); + + upvotes.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ArticleVote vote = new ArticleVote(); + vote.setArticle(articleId); + vote.setMagzine(article.getMagzineId()); + vote.setValue(1); + vote.setUser(userProfileStorage.getInt("userId", -1)); + + if(db.alreadyCastedVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), 1)) { + Toast.makeText(getApplicationContext(), "Already Upvoted!", Toast.LENGTH_SHORT ).show(); + } else { + if(db.alreadyCastedVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), -1)) { + db.deleteVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), -1); + currentDownvotes --; + totalDownvotes.setText(currentDownvotes.toString()); + } + + db.insertVote(vote); + currentUpvotes = Integer.valueOf(totalUpvotes.getText().toString()); + currentUpvotes ++; + totalUpvotes.setText(currentUpvotes.toString()); + } + + + } + }); + + downvotes = (ImageView) findViewById(R.id.downvote); + totalDownvotes = (TextView) findViewById(R.id.total_downvotes); + + currentDownvotes = db.getAllDownvotes(article.get_id(), article.getMagzineId()); + totalDownvotes.setText(currentDownvotes.toString()); + + downvotes.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + ArticleVote vote = new ArticleVote(); + vote.setArticle(articleId); + vote.setMagzine(article.getMagzineId()); + vote.setValue(-1); + vote.setUser(userProfileStorage.getInt("userId", -1)); + + if(db.alreadyCastedVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), -1)) { + Toast.makeText(getApplicationContext(), "Already Downvoted!", Toast.LENGTH_SHORT ).show(); + } + else { + if(db.alreadyCastedVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), 1)) { + db.deleteVote(vote.getUser(), vote.getArticle(), vote.getMagzine(), 1); + currentUpvotes --; + totalUpvotes.setText(currentUpvotes.toString()); + } + db.insertVote(vote); + currentDownvotes = Integer.valueOf(totalDownvotes.getText().toString()); + currentDownvotes++; + totalDownvotes.setText(currentDownvotes.toString()); + } + + + + } + }); + + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.publish_article); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent publishIntent = new Intent(ArticleReadingActivity.this, ArticlePublishActivity.class); + publishIntent.putExtra("articleId", articleId); + startActivity(publishIntent); + } + }); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + + getMenuInflater().inflate(R.menu.publish_article_menu, menu); + return super.onCreateOptionsMenu(menu); + } + + private void updateValues(){ + + title = (NastaleeqTextView) findViewById(R.id.article_read_act_title); + body = (NastaleeqTextView) findViewById(R.id.article_read_act_body); + + db = new LocalStorage(this, null, null, 1); + article = db.getArticle(articleId); + + title.setText(article.getArticleTitle()); + body.setText(article.getArticleBody()); + + body.setMovementMethod(new ScrollingMovementMethod()); + } + protected void onResume() { + super.onResume(); + updateValues(); + + } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + + int id = item.getItemId(); + + if (id == R.id.action_edit_article) { + + Intent editIntent = new Intent(this, NewArticleActivity.class); + editIntent.putExtra("articleId", articleId); + startActivity(editIntent); + + return true; + } + + return super.onOptionsItemSelected(item); + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/EpubReaderActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/EpubReaderActivity.java new file mode 100644 index 0000000..b410865 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/EpubReaderActivity.java @@ -0,0 +1,463 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.app.Activity; +import android.app.DialogFragment; +import android.app.FragmentTransaction; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.widget.LinearLayout; +import android.widget.Toast; + +import com.example.manan.enhancedurdureader.EpubReader.ChangeCSSMenu; +import com.example.manan.enhancedurdureader.EpubReader.EpubNavigator; +import com.example.manan.enhancedurdureader.EpubReader.LanguageChooser; +import com.example.manan.enhancedurdureader.EpubReader.SetPanelSize; +import com.example.manan.enhancedurdureader.EpubReader.SplitPanel; +import com.example.manan.enhancedurdureader.R; + +public class EpubReaderActivity extends AppCompatActivity { + + public EpubNavigator navigator; + protected int bookSelector; + protected int panelCount; + protected String[] settings; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_epub_reader); + + navigator = new EpubNavigator(2, this); + + panelCount = 0; + settings = new String[8]; + + // LOADSTATE + SharedPreferences preferences = getPreferences(MODE_PRIVATE); + loadState(preferences); + navigator.loadViews(preferences); + + + Intent intent = getIntent(); + String filePath = intent.getStringExtra("path"); + navigator.openBook(filePath,bookSelector); + + /*if (panelCount == 0) { + bookSelector = 0; + Intent goToChooser = new Intent(this, FileChooser.class); + startActivityForResult(goToChooser, 0); + }*/ + } + + protected void onResume() { + super.onResume(); + if (panelCount == 0) { + SharedPreferences preferences = getPreferences(MODE_PRIVATE); + navigator.loadViews(preferences); + } + } + + @Override + protected void onPause() { + super.onPause(); + SharedPreferences preferences = getPreferences(MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + saveState(editor); + editor.commit(); + } + + // load the selected book + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (panelCount == 0) { + SharedPreferences preferences = getPreferences(MODE_PRIVATE); + navigator.loadViews(preferences); + } + + if (resultCode == Activity.RESULT_OK) { + String path = data.getStringExtra("path"); + navigator.openBook(path, bookSelector); + } + } + + // ---- Menu + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.epub_reader_menu, menu); + return true; + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + + if (navigator.isParallelTextOn() == false + && navigator.exactlyOneBookOpen() == false) { + menu.findItem(R.id.meta1).setVisible(true); + menu.findItem(R.id.meta2).setVisible(true); + menu.findItem(R.id.toc1).setVisible(true); + menu.findItem(R.id.toc2).setVisible(true); + menu.findItem(R.id.FirstFront).setVisible(true); + menu.findItem(R.id.SecondFront).setVisible(true); + } + + if (navigator.exactlyOneBookOpen() == false) { + menu.findItem(R.id.Synchronize).setVisible(true); + menu.findItem(R.id.Align).setVisible(true); + // menu.findItem(R.id.SyncScroll).setVisible(true); + menu.findItem(R.id.StyleBook1).setVisible(true); + menu.findItem(R.id.StyleBook2).setVisible(true); + menu.findItem(R.id.firstAudio).setVisible(true); + menu.findItem(R.id.secondAudio).setVisible(true); + } + + if (navigator.exactlyOneBookOpen() == true + || navigator.isParallelTextOn() == true) { + menu.findItem(R.id.meta1).setVisible(false); + menu.findItem(R.id.meta2).setVisible(false); + menu.findItem(R.id.toc1).setVisible(false); + menu.findItem(R.id.toc2).setVisible(false); + menu.findItem(R.id.FirstFront).setVisible(false); + menu.findItem(R.id.SecondFront).setVisible(false); + } + + if (navigator.exactlyOneBookOpen() == true) { + menu.findItem(R.id.Synchronize).setVisible(false); + menu.findItem(R.id.Align).setVisible(false); + menu.findItem(R.id.SyncScroll).setVisible(false); + menu.findItem(R.id.StyleBook1).setVisible(false); + menu.findItem(R.id.StyleBook2).setVisible(false); + menu.findItem(R.id.firstAudio).setVisible(false); + menu.findItem(R.id.secondAudio).setVisible(false); + } + + // if there is only one view, option "changeSizes" is not visualized + if (panelCount == 1) + menu.findItem(R.id.changeSize).setVisible(false); + else + menu.findItem(R.id.changeSize).setVisible(true); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + + switch (item.getItemId()) { + case R.id.FirstEPUB: + bookSelector = 0; + /*Intent goToChooser1 = new Intent(this, FileChooser.class); + goToChooser1.putExtra(getString(R.string.second), + getString(R.string.time)); + startActivityForResult(goToChooser1, 0);*/ + return true; + + case R.id.SecondEPUB: + bookSelector = 1; + /*Intent goToChooser2 = new Intent(this, FileChooser.class); + goToChooser2.putExtra(getString(R.string.second), + getString(R.string.time)); + startActivityForResult(goToChooser2, 0);*/ + return true; + + case R.id.Front: + if (navigator.exactlyOneBookOpen() == true + || navigator.isParallelTextOn() == true) + chooseLanguage(0); + return true; + + case R.id.FirstFront: + chooseLanguage(0); + return true; + + case R.id.SecondFront: + if (navigator.exactlyOneBookOpen() == false) + chooseLanguage(1); + else + errorMessage(getString(R.string.error_onlyOneBookOpen)); + return true; + + case R.id.PconS: + try { + boolean yes = navigator.synchronizeView(1, 0); + if (!yes) { + errorMessage(getString(R.string.error_onlyOneBookOpen)); + } + } catch (Exception e) { + errorMessage(getString(R.string.error_cannotSynchronize)); + } + return true; + + case R.id.SconP: + try { + boolean ok = navigator.synchronizeView(0, 1); + if (!ok) { + errorMessage(getString(R.string.error_onlyOneBookOpen)); + } + } catch (Exception e) { + errorMessage(getString(R.string.error_cannotSynchronize)); + } + return true; + + case R.id.Synchronize: + + boolean sync = navigator.flipSynchronizedReadingActive(); + if (!sync) { + errorMessage(getString(R.string.error_onlyOneBookOpen)); + } + return true; + + case R.id.Metadata: + if (navigator.exactlyOneBookOpen() == true + || navigator.isParallelTextOn() == true) { + navigator.displayMetadata(0); + } else { + } + return true; + + case R.id.meta1: + if (!navigator.displayMetadata(0)) + errorMessage(getString(R.string.error_metadataNotFound)); + return true; + + case R.id.meta2: + if (!navigator.displayMetadata(1)) + errorMessage(getString(R.string.error_metadataNotFound)); + return true; + + case R.id.tableOfContents: + if (navigator.exactlyOneBookOpen() == true + || navigator.isParallelTextOn() == true) + navigator.displayTOC(0); + return true; + + case R.id.toc1: + if (!navigator.displayTOC(0)) + errorMessage(getString(R.string.error_tocNotFound)); + return true; + case R.id.toc2: + if (navigator.displayTOC(1)) + errorMessage(getString(R.string.error_tocNotFound)); + return true; + case R.id.changeSize: + try { + DialogFragment newFragment = new SetPanelSize(); + newFragment.show(getFragmentManager(), ""); + } catch (Exception e) { + errorMessage(getString(R.string.error_cannotChangeSizes)); + } + return true; + case R.id.Style: // work in progress... + try { + if (navigator.exactlyOneBookOpen() == true) { + DialogFragment newFragment = new ChangeCSSMenu(); + newFragment.show(getFragmentManager(), ""); + bookSelector = 0; + } + } catch (Exception e) { + errorMessage(getString(R.string.error_CannotChangeStyle)); + } + return true; + + case R.id.StyleBook1: + try { + { + DialogFragment newFragment = new ChangeCSSMenu(); + newFragment.show(getFragmentManager(), ""); + bookSelector = 0; + } + } catch (Exception e) { + errorMessage(getString(R.string.error_CannotChangeStyle)); + } + return true; + + case R.id.StyleBook2: + try { + { + DialogFragment newFragment = new ChangeCSSMenu(); + newFragment.show(getFragmentManager(), ""); + bookSelector = 1; + } + } catch (Exception e) { + errorMessage(getString(R.string.error_CannotChangeStyle)); + } + return true; + + /* + * case R.id.SyncScroll: syncScrollActivated = !syncScrollActivated; + * return true; + */ + + case R.id.audio: + if (navigator.exactlyOneBookOpen() == true) + if (!navigator.extractAudio(0)) + errorMessage(getString(R.string.no_audio)); + return true; + case R.id.firstAudio: + if (!navigator.extractAudio(0)) + errorMessage(getString(R.string.no_audio)); + return true; + case R.id.secondAudio: + if (!navigator.extractAudio(1)) + errorMessage(getString(R.string.no_audio)); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + // ---- + + // ---- Panels Manager + public void addPanel(SplitPanel p) { + FragmentTransaction fragmentTransaction = getFragmentManager() + .beginTransaction(); + fragmentTransaction.add(R.id.MainLayout, p, p.getTag()); + fragmentTransaction.commit(); + + panelCount++; + } + + public void attachPanel(SplitPanel p) { + FragmentTransaction fragmentTransaction = getFragmentManager() + .beginTransaction(); + fragmentTransaction.attach(p); + fragmentTransaction.commit(); + + panelCount++; + } + + public void detachPanel(SplitPanel p) { + FragmentTransaction fragmentTransaction = getFragmentManager() + .beginTransaction(); + fragmentTransaction.detach(p); + fragmentTransaction.commit(); + + panelCount--; + } + + public void removePanelWithoutClosing(SplitPanel p) { + FragmentTransaction fragmentTransaction = getFragmentManager() + .beginTransaction(); + fragmentTransaction.remove(p); + fragmentTransaction.commit(); + + panelCount--; + } + + public void removePanel(SplitPanel p) { + FragmentTransaction fragmentTransaction = getFragmentManager() + .beginTransaction(); + fragmentTransaction.remove(p); + fragmentTransaction.commit(); + + panelCount--; + if (panelCount <= 0) + finish(); + } + + // ---- + + // ---- Language Selection + public void chooseLanguage(int book) { + + String[] languages; + languages = navigator.getLanguagesBook(book); + if (languages.length == 2) + refreshLanguages(book, 0, 1); + else if (languages.length > 0) { + Bundle bundle = new Bundle(); + bundle.putInt(getString(R.string.tome), book); + bundle.putStringArray(getString(R.string.lang), languages); + + LanguageChooser langChooser = new LanguageChooser(); + langChooser.setArguments(bundle); + langChooser.show(getFragmentManager(), ""); + } else { + errorMessage(getString(R.string.error_noOtherLanguages)); + } + } + + public void refreshLanguages(int book, int first, int second) { + navigator.parallelText(book, first, second); + } + + // ---- + + // ---- Change Style + public void setCSS() { + navigator.changeCSS(bookSelector, settings); + } + + public void setBackColor(String my_backColor) { + settings[1] = my_backColor; + } + + public void setColor(String my_color) { + settings[0] = my_color; + } + + public void setFontType(String my_fontFamily) { + settings[2] = my_fontFamily; + } + + public void setFontSize(String my_fontSize) { + settings[3] = my_fontSize; + } + + public void setLineHeight(String my_lineHeight) { + if (my_lineHeight != null) + settings[4] = my_lineHeight; + } + + public void setAlign(String my_Align) { + settings[5] = my_Align; + } + + public void setMarginLeft(String mLeft) { + settings[6] = mLeft; + } + + public void setMarginRight(String mRight) { + settings[7] = mRight; + } + + public void setWordWrap() {settings[7] = "word-wrap:break-word;"; } + + // ---- + + // change the views size, changing the weight + public void changeViewsSize(float weight) { + navigator.changeViewsSize(weight); + } + + public int getHeight() { + LinearLayout main = (LinearLayout) findViewById(R.id.MainLayout); + return main.getMeasuredHeight(); + } + + public int getWidth() { + LinearLayout main = (LinearLayout) findViewById(R.id.MainLayout); + return main.getWidth(); + } + + // Save/Load State + protected void saveState(SharedPreferences.Editor editor) { + navigator.saveState(editor); + } + + protected void loadState(SharedPreferences preferences) { + if (!navigator.loadState(preferences)) + errorMessage(getString(R.string.error_cannotLoadState)); + } + + public void errorMessage(String message) { + Context context = getApplicationContext(); + Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); + toast.show(); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/MainActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/MainActivity.java new file mode 100755 index 0000000..5b0b576 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/MainActivity.java @@ -0,0 +1,159 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.content.Intent; +import android.os.Bundle; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.design.widget.TabLayout; +import android.view.View; +import android.support.design.widget.NavigationView; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; + +import com.example.manan.enhancedurdureader.Adapters.PagerAdapter; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.CustomViews.CustomViewPager; +import com.example.manan.enhancedurdureader.Fragments.MagazinesFragment; +import com.example.manan.enhancedurdureader.R; + + +public class MainActivity extends AppCompatActivity + implements NavigationView.OnNavigationItemSelectedListener { + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + InitializeTabs(); + + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) + .setAction("Action", null).show(); + } + }); + + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( + this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.setDrawerListener(toggle); + toggle.syncState(); + + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + navigationView.setNavigationItemSelectedListener(this); + } + + @Override + public void onBackPressed() { + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + super.onBackPressed(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_create_New_Magazine) { + Intent newMagzine = new Intent(this, NewMagazineActivity.class); + startActivity(newMagzine); + return true; + } + if (id == R.id.action_create_New_Article) { + + Intent newArticle = new Intent(this, NewArticleActivity.class); + startActivity(newArticle); + return true; + } + + return super.onOptionsItemSelected(item); + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + // Handle navigation view item clicks here. + int id = item.getItemId(); + + if (id == R.id.usr_profile) { + //will start the user profile activity here + + + } + + + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + return true; + } + + @Override + protected void onResume() { + super.onResume(); + MagazinesFragment fragment = (MagazinesFragment) adapter.getMagazineFragment(); + if(fragment!=null) + fragment.UpdateMagazine(); + + } + PagerAdapter adapter; + private void InitializeTabs() + { + final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); + tabLayout.addTab(tabLayout.newTab().setText("Books")); + tabLayout.addTab(tabLayout.newTab().setText("Magazines")); + tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); + + + final CustomViewPager viewPager = (CustomViewPager) findViewById(R.id.pager); + adapter = new PagerAdapter + (getSupportFragmentManager(), 2); + viewPager.setAdapter(adapter); + viewPager.setSwipeable(false); + + + + tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + @Override + public void onTabSelected(TabLayout.Tab tab) { + viewPager.setCurrentItem(tab.getPosition()); + } + + @Override + public void onTabUnselected(TabLayout.Tab tab) { + + } + + @Override + public void onTabReselected(TabLayout.Tab tab) { + + } + }); + + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewArticleActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewArticleActivity.java new file mode 100644 index 0000000..14a8887 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewArticleActivity.java @@ -0,0 +1,177 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.database.sqlite.SQLiteException; +import android.net.Uri; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.support.annotation.Nullable; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Toast; + +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.CustomViews.NastaleeqEditText; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +public class NewArticleActivity extends AppCompatActivity { + + LocalStorage db; + NastaleeqEditText _articleTitle; + NastaleeqEditText _articleBody; + String _articleCoverURI; + Integer articleId; + Article article; + SharedPreferences userProfileStorage; + public static final String USER_PROFILE_STORAGE = "UserProfileStorage" ; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_new_article); + + Intent articleIntent = getIntent(); + articleId = articleIntent.getIntExtra("articleId", -1); + + db = new LocalStorage(this, null, null, 1); + if(articleId==-1) { + _articleTitle = (NastaleeqEditText) findViewById(R.id.new_article_title); + _articleBody = (NastaleeqEditText) findViewById(R.id.new_article_body); + } else { + article = db.getArticle(articleId); + + _articleTitle = (NastaleeqEditText) findViewById(R.id.new_article_title); + _articleTitle.setText(article.getArticleTitle()); + + _articleBody = (NastaleeqEditText) findViewById(R.id.new_article_body); + _articleBody.setText(article.getArticleBody()); + } + + FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.save_article); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + saveArticle(); + } + }); + + + } + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.new_article_menu, menu); + return true; + } + + //save article to database of articles + public void saveArticle(){ + + userProfileStorage = getSharedPreferences(USER_PROFILE_STORAGE, Context.MODE_PRIVATE); + if(articleId == -1) { + article = new Article(); + article.setArticleTitle(_articleTitle.getText().toString()); + article.setArticleBody(_articleBody.getText().toString()); + article.setArticleCover(_articleCoverURI); + article.setAuthorId(userProfileStorage.getInt("userId", -1)); + + try { + + db.insertArticle(article); + Toast.makeText(this, "Article Saved Successfully", Toast.LENGTH_SHORT).show(); + } catch (SQLiteException e) { + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); + } + } else { + + article.setArticleTitle(_articleTitle.getText().toString()); + article.setArticleBody(_articleBody.getText().toString()); + article.setArticleCover(_articleCoverURI); + article.setAuthorId(userProfileStorage.getInt("userId", -1)); + + try { + db.updateArticle(article); + Toast.makeText(this, "Article Updated!"+String.valueOf(article.getAuthorId()), Toast.LENGTH_SHORT).show(); + } catch (SQLiteException e) { + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); + } + } + + + } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_add_article_cover) { + Intent intent = new Intent(); + intent.setType("image/*"); + intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(intent, 1); + return true; + } + if (id == R.id.action_create_New_Article) { + + Intent newArticle = new Intent(this, NewArticleActivity.class); + startActivity(newArticle); + return true; + } + + + return super.onOptionsItemSelected(item); + } + + @SuppressLint("NewApi") + public static String getRealPathFromURI(Context context, Uri uri){ + String filePath = ""; + String wholeID = DocumentsContract.getDocumentId(uri); + + // Split at colon, use second item in the array + String id = wholeID.split(":")[1]; + + String[] column = { MediaStore.Images.Media.DATA }; + + // where id is equal to + String sel = MediaStore.Images.Media._ID + "=?"; + + Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + column, sel, new String[]{ id }, null); + + int columnIndex = cursor.getColumnIndex(column[0]); + + if (cursor.moveToFirst()) { + filePath = cursor.getString(columnIndex); + } + cursor.close(); + return filePath; + } + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + if (requestCode == 1) { + + Uri selectedImage = data.getData(); + String[] filePathColumn = { MediaStore.Images.Media.DATA }; + Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); + cursor.moveToFirst(); + int columnIndex = cursor.getColumnIndex(filePathColumn[0]); + _articleCoverURI = cursor.getString(columnIndex); + cursor.close(); + } + } + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewMagazineActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewMagazineActivity.java new file mode 100644 index 0000000..cd2f9ed --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/NewMagazineActivity.java @@ -0,0 +1,112 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.content.Intent; +import android.database.Cursor; +import android.database.sqlite.SQLiteException; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.provider.MediaStore; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.Toast; + +import com.bumptech.glide.Glide; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.CustomViews.NastaleeqEditText; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +import java.io.File; + +public class NewMagazineActivity extends AppCompatActivity { + + NastaleeqEditText magNameView; + ImageView magCoverView; + Button magAddBtn; + Button magDiscardBtn; + + LocalStorage db; + Magazine newMagzine; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_new_magazine); + + newMagzine = new Magazine(); + db = new LocalStorage(this, null, null, 1); + + magNameView = (NastaleeqEditText) findViewById(R.id.magzine_name); + magCoverView = (ImageView) findViewById(R.id.magzine_cover); + magAddBtn = (Button) findViewById(R.id.add_magzine_btn); + magDiscardBtn = (Button) findViewById(R.id.discard_magzine_btn); + + magCoverView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + Intent intent = new Intent(); + intent.setType("image/*"); + intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(intent, 1); + + } + }); + + magAddBtn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + saveMagzine(); + + } + }); + + magDiscardBtn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + NewMagazineActivity.this.finish(); + } + }); + } + + private void saveMagzine(){ + newMagzine.setEditorId(1); + newMagzine.setTitleResId(magNameView.getText().toString()); + + try { + + db.insertMagzine(newMagzine); + Toast.makeText(this, "Magazine Saved Successfully", Toast.LENGTH_SHORT).show(); + } catch (SQLiteException e) { + Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); + } + + + } + public void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK) { + if (requestCode == 1) { + Uri selectedImage = data.getData(); + String[] filePathColumn = { MediaStore.Images.Media.DATA }; + Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); + cursor.moveToFirst(); + int columnIndex = cursor.getColumnIndex(filePathColumn[0]); + newMagzine.setImageResId( cursor.getString(columnIndex)); + cursor.close(); + + if(newMagzine.getImageResId()!=null) { + /*BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 3; + + magCoverView.setImageBitmap(BitmapFactory.decodeFile(newMagzine.getImageResId(),options)); + */ + Glide.with(this).load(new File(newMagzine.getImageResId())).into(magCoverView); + } + } + } + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Activities/SegmentedBookReaderActivity.java b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/SegmentedBookReaderActivity.java new file mode 100644 index 0000000..b7dc28c --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Activities/SegmentedBookReaderActivity.java @@ -0,0 +1,359 @@ +package com.example.manan.enhancedurdureader.Activities; + +import android.app.ProgressDialog; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.os.AsyncTask; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.support.v7.widget.Toolbar; +import android.util.DisplayMetrics; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.WindowManager; +import android.widget.ImageView; +import android.widget.RelativeLayout; +import android.widget.Toast; + +import com.bumptech.glide.GenericRequestBuilder; +import com.bumptech.glide.Glide; +import com.bumptech.glide.load.ResourceDecoder; +import com.bumptech.glide.load.engine.DiskCacheStrategy; +import com.bumptech.glide.load.engine.Resource; +import com.bumptech.glide.load.model.StreamEncoder; +import com.bumptech.glide.load.model.stream.StreamUriLoader; +import com.bumptech.glide.load.resource.SimpleResource; +import com.bumptech.glide.load.resource.drawable.GlideDrawable; +import com.bumptech.glide.request.animation.GlideAnimation; +import com.bumptech.glide.request.target.SimpleTarget; +import com.bumptech.glide.request.target.SizeReadyCallback; +import com.example.manan.enhancedurdureader.ApplicationEntities.BookInfo; +import com.example.manan.enhancedurdureader.ApplicationEntities.PageInfo; +import com.example.manan.enhancedurdureader.ApplicationEntities.PageOffset; +import com.example.manan.enhancedurdureader.ApplicationEntities.SegmentedBook; +import com.example.manan.enhancedurdureader.R; +import com.squareup.picasso.Picasso; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; + +public class SegmentedBookReaderActivity extends AppCompatActivity { + + BookInfo bookInfo = new BookInfo(); + PageInfo pageInfo = new PageInfo(); + PageOffset pageOffset = new PageOffset(); + File[] files = null; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_segmented_book_reader); + //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + //setSupportActionBar(toolbar); + + /*final ImageView iv =new ImageView(this); + ViewTreeObserver vto = iv.getViewTreeObserver(); + vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + public boolean onPreDraw() { + iv.getViewTreeObserver().removeOnPreDrawListener(this); + final int Height = iv.getMeasuredHeight(); + final int Width = iv.getMeasuredWidth(); + + pageInfo.pageWidth = pageInfo.pageWidth/(bookInfo.ligatures.get(0).getWidth()/Width); + + pageInfo.pageHeight = pageInfo.pageHeight/(bookInfo.ligatures.get(0).getHeight()/Height); + + RenderPage(pageOffset.startingLigatureIndex); + return true; + } + });*/ + Intent intent = getIntent(); + String filePath = intent.getStringExtra("path"); + + + SetScreenSize(); + OpenLigatureFiles(filePath); + LoadLigatures(); + RenderPage(pageOffset.endingLigatureIndex); + + /*iv.setImageBitmap(bookInfo.ligatures.get(0)); + RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.activity_segmented_book_reader); + RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(bookInfo.ligatures.get(0).getWidth(), bookInfo.ligatures.get(0).getHeight()); + layout.addView(iv,params);*/ + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + //getMenuInflater().inflate(R.menu.menu_main, menu); + return true; + } + + + + + + + //====================================================================================================== + private void SetScreenSize() { + + DisplayMetrics displayMetrics = new DisplayMetrics(); + + WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(getApplicationContext().WINDOW_SERVICE); + + windowmanager.getDefaultDisplay().getMetrics(displayMetrics); + + pageInfo.pageHeight = Math.round(displayMetrics.heightPixels / displayMetrics.density); + pageInfo.pageWidth = Math.round(displayMetrics.widthPixels / displayMetrics.density); + + pageInfo.pageHeight -= 50; + pageInfo.pageWidth -= 50; + + } + + private void RenderPage(int startingLigatureIndex) { + RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.activity_segmented_book_reader); + + + layout.removeAllViews(); + pageInfo.previousLineFirstRenderedLigature = pageInfo.lastRenderedLigature = null; + + int totalLineWidth = 0; + int totalPageHeight = 0; + int i = 0; + int accMargin = bookInfo.margin; + + pageOffset.startingLigatureIndex = startingLigatureIndex; + totalLineWidth += bookInfo.ligatures.get(startingLigatureIndex).getHeight(); + for (int j = startingLigatureIndex; j < bookInfo.ligatures.size(); j++) { + Bitmap image = bookInfo.ligatures.get(j); + ImageView iView = new ImageView(SegmentedBookReaderActivity.this); + iView.setId(View.generateViewId()); + iView.setBackground(new BitmapDrawable(getResources(), image)); + + totalLineWidth += image.getWidth(); + RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(image.getWidth(), image.getHeight()); + + if (pageInfo.lastRenderedLigature == null) { + params.addRule(RelativeLayout.ALIGN_PARENT_END, RelativeLayout.TRUE); + params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); + params.setMargins(0, bookInfo.margin, 0, 0); + pageInfo.previousLineFirstRenderedLigature = iView; + } else if (totalLineWidth >= pageInfo.pageWidth) { + params.addRule(RelativeLayout.BELOW, pageInfo.previousLineFirstRenderedLigature.getId()); + params.addRule(RelativeLayout.ALIGN_PARENT_END, RelativeLayout.TRUE); + int maxHeight = getMaxHeightLigature(i); + if (maxHeight > bookInfo.margin) { + //params.setMargins(0,bookInfo.margin+(maxHeight - bookInfo.margin - iView.getHeight()),0,0); + params.setMargins(0, bookInfo.margin + maxHeight, 0, 0); + totalPageHeight += bookInfo.margin + 2 * maxHeight; + } else { + params.setMargins(0, bookInfo.margin, 0, 0); + totalPageHeight += bookInfo.margin; + } + pageInfo.previousLineFirstRenderedLigature = iView; + totalLineWidth = 0; + + //accMargin += bookInfo.margin*2; + } else { + params.addRule(RelativeLayout.ALIGN_BOTTOM, pageInfo.lastRenderedLigature.getId()); + params.addRule(RelativeLayout.START_OF, pageInfo.lastRenderedLigature.getId()); + + + } + + //if((i+1) >= ((bookInfo.maxLinesInPage+1) * bookInfo.maxLigaturesInLine)) { + if (totalPageHeight >= pageInfo.pageHeight) { + pageOffset.endingLigatureIndex = j - 1; + break; + } + + layout.addView(iView, params); + pageInfo.lastRenderedLigature = iView; + i++; + + } + + + } + + int getMaxHeightLigature(int startIndex) { + int maxHeight = bookInfo.ligatures.get(0).getHeight(); + for (int i = startIndex; i < bookInfo.maxLigaturesInLine; i++) { + if (maxHeight < bookInfo.ligatures.get(i).getHeight()) + maxHeight = bookInfo.ligatures.get(i).getHeight(); + } + return maxHeight; + } + + private void OpenLigatureFiles(String path) { + files = new File(path).listFiles(); + } + + private void LoadLigatures() { + int width = 0; + int height = 0; + bookInfo.ligatures.clear(); + + + for (int i = 0; i < files.length; i++) { + Bitmap bitmap = BitmapFactory.decodeFile(files[i].getPath()); + + + width += bitmap.getWidth() * bookInfo.zoomSize; + //height += bitmap.getHeight() * bookInfo.zoomSize; + height = height < bitmap.getHeight() * bookInfo.zoomSize ? bitmap.getHeight() * bookInfo.zoomSize : height; + + Bitmap scaledBitmap = Bitmap.createScaledBitmap( + bitmap, bitmap.getWidth() * bookInfo.zoomSize, bitmap.getHeight() * bookInfo.zoomSize, false); + + bookInfo.ligatures.add(scaledBitmap); + } + bookInfo.maxLigaturesInLine = pageInfo.pageWidth / (width / bookInfo.ligatures.size()); + bookInfo.maxLinesInPage = pageInfo.pageHeight / (bookInfo.margin + 2 * height);//bookInfo.maxLigaturesInLine * (pageInfo.pageHeight/(height/bookInfo.ligatures.size())); + } + + float oldDist = 1f; + static final int NONE = 0; + static final int ZOOM = 1; + int mode = NONE; + float tempZoomInCount = 0; + float tempZoomOutCount = 1; + + private float x1, x2; + static final int MIN_DISTANCE = 150; + + + @Override + public boolean onTouchEvent(MotionEvent event) { + switch (event.getAction() & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_DOWN: + x1 = event.getX(); + break; + case MotionEvent.ACTION_UP: + if(mode != ZOOM) { + x2 = event.getX(); + float deltaX = x2 - x1; + if (Math.abs(deltaX) > MIN_DISTANCE) { + if (x2 > x1) { + //Toast.makeText(this, "Left to Right swipe [Next]", Toast.LENGTH_SHORT).show (); + pageOffset.pageLigaturesCount.push(pageOffset.endingLigatureIndex - pageOffset.startingLigatureIndex + 1); + RenderPage(pageOffset.endingLigatureIndex + 1); + } else { + //Toast.makeText(this, "Right to Left swipe [Previous]", Toast.LENGTH_SHORT).show (); + if(pageOffset.pageLigaturesCount.size()>0) { + Integer lastPageLiagturesCount = pageOffset.pageLigaturesCount.pop(); + RenderPage(pageOffset.startingLigatureIndex - lastPageLiagturesCount); + } + } + } + } + break; + case MotionEvent.ACTION_POINTER_DOWN: + oldDist = spacing(event); + if (oldDist > 10f) { + mode = ZOOM; + } + break; + case MotionEvent.ACTION_POINTER_UP: + mode = NONE; + break; + + case MotionEvent.ACTION_MOVE: + if(mode == ZOOM) { + + float newDist = spacing(event); + if(newDist > 10f) + { + float scale = newDist/oldDist; + if(scale > 1) + { + if(bookInfo.zoomSize<3) + { + tempZoomInCount+=0.5; + if(tempZoomInCount == 1) + { + mode = NONE; + bookInfo.zoomSize++; + tempZoomInCount =0; + + LoadAndRender zoomIn = new LoadAndRender(); + Toast.makeText(this, String.valueOf(bookInfo.zoomSize), Toast.LENGTH_SHORT).show (); + zoomIn.execute(); + } + } + } + else + { + scale = 0.95f; + if(bookInfo.zoomSize>1) + { + tempZoomOutCount-=0.5; + if(tempZoomOutCount == 0) + { + mode = NONE; + bookInfo.zoomSize--; + tempZoomOutCount =1; + + LoadAndRender zoomOut = new LoadAndRender(); + Toast.makeText(this, String.valueOf(bookInfo.zoomSize), Toast.LENGTH_SHORT).show (); + zoomOut.execute(); + } + } + } + } + } + } + return super.onTouchEvent(event); + } + private class LoadAndRender extends AsyncTask { + private ProgressDialog dialog = new ProgressDialog(SegmentedBookReaderActivity.this); + private Boolean stop = false; + @Override + protected Void doInBackground(Void... params) { + try { + + LoadLigatures(); + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + @Override + protected void onPostExecute(Void result) { + if (dialog.isShowing()) { + dialog.dismiss(); + RenderPage(pageOffset.startingLigatureIndex); + } + } + + @Override + protected void onPreExecute() { + dialog.setMessage("Please Wait...."); + dialog.show(); + + + } + + @Override + protected void onProgressUpdate(Void... values) { + } + } + + private float spacing(MotionEvent event) { + float x = event.getX(0) - event.getX(1); + float y = event.getY(0) - event.getY(1); + return (int) Math.sqrt(x * x + y * y); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticleAdapter.java b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticleAdapter.java new file mode 100644 index 0000000..256cd47 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticleAdapter.java @@ -0,0 +1,127 @@ +package com.example.manan.enhancedurdureader.Adapters; + +import android.app.ProgressDialog; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.os.AsyncTask; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import com.bumptech.glide.Glide; +import com.example.manan.enhancedurdureader.Activities.SegmentedBookReaderActivity; +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +import org.w3c.dom.Text; + +import java.io.File; +import java.util.ArrayList; + +/** + * Created by manan on 3/9/17. + */ + +public class ArticleAdapter extends BaseAdapter { + private ArrayList
mData = new ArrayList<>(0); + private Context mContext; + + View rowView; + + public ArticleAdapter(Context context) { + mContext = context; + } + + public void setData(ArrayList
data) { + mData = data; + } + + @Override + public int getCount() { + return mData.size(); + } + + @Override + public Object getItem(int pos) { + return mData.get(pos); + } + + @Override + public long getItemId(int pos) { + return pos; + } + TextView voteCount; + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + rowView = convertView; + + if (rowView == null) { + LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + rowView = inflater.inflate(R.layout.article_layout, null); + + ImageView articleTitlePage = (ImageView) rowView.findViewById(R.id.article_title_page); + /*BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 2; + + articleTitlePage.setImageBitmap(BitmapFactory.decodeFile(mData.get(position).getArticleCover(),options)); + */ + if(mData.get(position).getArticleCover() != null) + Glide.with(mContext).load(new File(mData.get(position%mData.size()).getArticleCover())).into(articleTitlePage); + + } + + voteCount = (TextView) rowView.findViewById(R.id.article_vote_count); + + //new SetVotesTask().execute(position); + LocalStorage voteDb = new LocalStorage(mContext, null, null, 1); + vtCount = (voteDb.getAllUpvotes(mData.get(position%mData.size()).get_id(), mData.get(position%mData.size()).getMagzineId())) - (voteDb.getAllDownvotes(mData.get(position%mData.size()).get_id(), mData.get(position%mData.size()).getMagzineId())); + + + + voteCount.setText(vtCount.toString()); + + + return rowView; + } + Integer vtCount = 0; + + private class SetVotesTask extends AsyncTask { + @Override + protected String doInBackground(Integer... params) { + int position = params[0]; + + LocalStorage voteDb = new LocalStorage(mContext, null, null, 1); + vtCount = (voteDb.getAllUpvotes(mData.get(position%mData.size()).get_id(), mData.get(position%mData.size()).getMagzineId())) - (voteDb.getAllDownvotes(mData.get(position%mData.size()).get_id(), mData.get(position%mData.size()).getMagzineId())); + + + return "Executed"; + } + + @Override + protected void onPostExecute(String result) { + + voteCount.setText(Integer.toString(vtCount)); + + + } + + @Override + protected void onPreExecute() { + + + } + + @Override + protected void onProgressUpdate(Void... values) {} + } + + + + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticlePublishAdapter.java b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticlePublishAdapter.java new file mode 100644 index 0000000..6ee82f5 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/ArticlePublishAdapter.java @@ -0,0 +1,119 @@ +package com.example.manan.enhancedurdureader.Adapters; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +import java.util.ArrayList; +import java.util.Hashtable; + +/** + * Created by manan on 3/10/17. + */ + +public class ArticlePublishAdapter extends BaseAdapter { + private ArrayList mData = new ArrayList(0); + private Context mContext; + ArrayList
articles = new ArrayList
(); + boolean hasLoaded = false; + Hashtable imageCache = new Hashtable(); + public ArticlePublishAdapter(Context context) { + + mContext = context; + + } + + public void setData(ArrayList data) { + mData = data; + } + + @Override + public int getCount() { + return mData.size(); + } + + @Override + public Object getItem(int pos) { + return mData.get(pos); + } + + @Override + public long getItemId(int pos) { + return pos; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View rowView = convertView; + LoadArticles(); + + if (rowView == null) { + LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + rowView = inflater.inflate(R.layout.publish_magazine_layout, null); + + ImageView magazineTitlePage = (ImageView) rowView.findViewById(R.id.publish_magazine_title_page); + + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 3; + + Bitmap image; + if(!imageCache.containsKey(position)) { + image = BitmapFactory.decodeFile(mData.get(position).getImageResId(), options); + + } + else + image = imageCache.get(position); + + int magazineID = mData.get(position).get_id(); + if(image == null && magazineID == 2) + magazineTitlePage.setImageResource(R.drawable.all_articles_magazine); + else if(image == null && magazineID ==1 ) + magazineTitlePage.setImageResource(R.drawable.saved_articles_magazine); + else { + magazineTitlePage.setImageBitmap(image); + imageCache.put(position,image); + + } + } + + + Integer articleCount = 0; + for (Article article:articles) { + if(article.getMagzineId() == mData.get(position).get_id()) + articleCount++; + } + if (mData.get(position).get_id() == 2) { + articleCount = articles.size(); + } else if(mData.get(position).get_id() == 1){ + articleCount = 0; + for (Article article:articles) { + if(article.getMagzineId() == 0) + articleCount++; + } + } + + + return rowView; + } + void LoadArticles() + { + if(!hasLoaded) + { + LocalStorage voteDb = new LocalStorage(mContext, null, null, 1); + articles = voteDb.getAllArticles(); + hasLoaded = true; + } + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/BooksAdapter.java b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/BooksAdapter.java new file mode 100755 index 0000000..03ea398 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/BooksAdapter.java @@ -0,0 +1,64 @@ +package com.example.manan.enhancedurdureader.Adapters; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import com.example.manan.enhancedurdureader.ApplicationEntities.Book; +import com.example.manan.enhancedurdureader.R; + +import org.w3c.dom.Text; + +import java.util.ArrayList; + +public class BooksAdapter extends BaseAdapter { + + private ArrayList mData = new ArrayList<>(0); + private Context mContext; + + public BooksAdapter(Context context) { + mContext = context; + } + + public void setData(ArrayList data) { + mData = data; + } + + @Override + public int getCount() { + return mData.size(); + } + + @Override + public Object getItem(int pos) { + return mData.get(pos); + } + + @Override + public long getItemId(int pos) { + return pos; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View rowView = convertView; + + if (rowView == null) { + LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + rowView = inflater.inflate(R.layout.book_layout, null); + + ImageView bookTitlePage = (ImageView) rowView.findViewById(R.id.book_title_page); + bookTitlePage.setImageBitmap(mData.get(position).BookTittlePage); + + return rowView; + } + + return rowView; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/MagazineAdapter.java b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/MagazineAdapter.java new file mode 100644 index 0000000..1081013 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/MagazineAdapter.java @@ -0,0 +1,139 @@ +package com.example.manan.enhancedurdureader.Adapters; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.media.Image; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import com.bumptech.glide.Glide; +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +import org.w3c.dom.Text; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +/** + * Created by manan on 3/9/17. + */ + +public class MagazineAdapter extends BaseAdapter { + + private ArrayList mData = new ArrayList(0); + private Context mContext; + ArrayList
articles = new ArrayList
(); + boolean hasLoaded = false; + Hashtable imageCache = new Hashtable(); + public MagazineAdapter(Context context) { + + mContext = context; + + } + + public void setData(ArrayList data) { + mData = data; + } + + @Override + public int getCount() { + return mData.size(); + } + + @Override + public Object getItem(int pos) { + return mData.get(pos); + } + + @Override + public long getItemId(int pos) { + return pos; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + + View rowView = convertView; + LoadArticles(); + + if (rowView == null) { + LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + rowView = inflater.inflate(R.layout.magazine_layout, null); + + ImageView magazineTitlePage = (ImageView) rowView.findViewById(R.id.magazine_title_page); + + /*Bitmap image; + /*BitmapFactory.Options options = new BitmapFactory.Options(); + options.inSampleSize = 3; + + if(!imageCache.containsKey(position)) { + image = BitmapFactory.decodeFile(mData.get(position).getImageResId(), options); + + } + else + image = imageCache.get(position); + + int magazineID = mData.get(position).get_id(); + if(image == null && magazineID == 2) + magazineTitlePage.setImageResource(R.drawable.all_articles_magazine); + else if(image == null && magazineID ==1 ) + magazineTitlePage.setImageResource(R.drawable.saved_articles_magazine); + else { + magazineTitlePage.setImageBitmap(image); + imageCache.put(position,image); + + }*/ + int magazineID = mData.get(position%mData.size()).get_id(); + if(magazineID == 2) + Glide.with(mContext).load(R.drawable.all_articles_magazine).into(magazineTitlePage); + else if(magazineID ==1 ) + Glide.with(mContext).load(R.drawable.saved_articles_magazine).into(magazineTitlePage); + else { + Glide.with(mContext).load(new File(mData.get(position%mData.size()).getImageResId())).skipMemoryCache(false).into(magazineTitlePage); + } + + } + + + Integer articleCount = 0; + for (Article article:articles) { + if(article.getMagzineId() == mData.get(position%mData.size()).get_id()) + articleCount++; + } + if (mData.get(position%mData.size()).get_id() == 2) { + articleCount = articles.size(); + } else if(mData.get(position%mData.size()).get_id() == 1){ + articleCount = 0; + for (Article article:articles) { + if(article.getMagzineId() == 0) + articleCount++; + } + } + TextView voteCount = (TextView)rowView.findViewById(R.id.vote_count); + voteCount.setText(Integer.toString(articleCount)); + + return rowView; + } + void LoadArticles() + { + if(!hasLoaded) + { + LocalStorage voteDb = new LocalStorage(mContext, null, null, 1); + articles = voteDb.getAllArticles(); + hasLoaded = true; + } + } + + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/PagerAdapter.java b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/PagerAdapter.java new file mode 100755 index 0000000..e7341aa --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Adapters/PagerAdapter.java @@ -0,0 +1,56 @@ +package com.example.manan.enhancedurdureader.Adapters; + +/** + * Created by manan on 3/7/17. + */ + +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentStatePagerAdapter; + +import com.example.manan.enhancedurdureader.Fragments.BooksFragment; +import com.example.manan.enhancedurdureader.Fragments.MagazinesFragment; + +import java.util.ArrayList; + +public class PagerAdapter extends FragmentStatePagerAdapter { + int mNumOfTabs; + + static ArrayList fragments = new ArrayList(); + public PagerAdapter(FragmentManager fm, int NumOfTabs) { + super(fm); + this.mNumOfTabs = NumOfTabs; + } + + @Override + public Fragment getItem(int position) { + + switch (position) { + case 0: + if(fragments.size()>0 &&fragments.get(0) != null) + return fragments.get(0); + BooksFragment tab1 = new BooksFragment(); + fragments.add(tab1); + return tab1; + case 1: + if(fragments.size()>1 &&fragments.get(1) != null) + return fragments.get(1); + MagazinesFragment tab2 = new MagazinesFragment(); + fragments.add(tab2); + return tab2; + default: + return null; + } + } + + @Override + public int getCount() { + return mNumOfTabs; + } + public Fragment getMagazineFragment() + { + if(fragments.size()>1) + return fragments.get(1); + return null; + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Article.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Article.java new file mode 100644 index 0000000..6367a72 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Article.java @@ -0,0 +1,78 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import com.bumptech.glide.Glide; + +/** + * Created by manan on 3/9/17. + */ + +public class Article { + + private int _id; + private int magzineId; + private String articleTitle; + private String articleBody; + public String articleCover; + private int authorId; + + + public int getAuthorId() { + return authorId; + } + + public Article() { + } + + public void setAuthorId(int authorId) { + this.authorId = authorId; + } + + public Article(String articleTitle, String articleBody, String articleCover, int magzine, int author){ + this.articleTitle = articleTitle; + this.articleBody = articleBody; + this.articleCover = articleCover; + this.magzineId = magzine; + this.authorId = author; + } + + public void setMagzineId(int magzineId) { + this.magzineId = magzineId; + } + + public void set_id(int _id) { + this._id = _id; + } + + public void setArticleTitle(String articleTitle) { + this.articleTitle = articleTitle; + } + + public void setArticleBody(String articleBody) { + this.articleBody = articleBody; + } + + public void setArticleCover(String articleCover) { + this.articleCover = articleCover; + } + + public int getMagzineId() { + return magzineId; + } + + public int get_id() { + return _id; + } + + public String getArticleTitle() { + return articleTitle; + } + + public String getArticleBody() { + return articleBody; + } + + public String getArticleCover() { + return articleCover; + } +} + diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/ArticleVote.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/ArticleVote.java new file mode 100644 index 0000000..53f8ff6 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/ArticleVote.java @@ -0,0 +1,67 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +/** + * Created by manan on 3/9/17. + */ + +public class ArticleVote { + + int _id, + value, + downvotes, + magzine, + article, + user; + + public int totalVotes(){ + return value -downvotes; + } + public int get_id() { + return _id; + } + + public void set_id(int _id) { + this._id = _id; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public int getDownvotes() { + return downvotes; + } + + public void setDownvotes(int downvotes) { + this.downvotes = downvotes; + } + + public int getMagzine() { + return magzine; + } + + public void setMagzine(int magzine) { + this.magzine = magzine; + } + + public int getArticle() { + return article; + } + + public void setArticle(int article) { + this.article = article; + } + + public int getUser() { + return user; + } + + public void setUser(int user) { + this.user = user; + } +} + diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Book.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Book.java new file mode 100755 index 0000000..acb30f7 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Book.java @@ -0,0 +1,16 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import android.graphics.Bitmap; + +/** + * Created by manan on 3/7/17. + */ + +public class Book { + public String BookTittle; + public Bitmap BookTittlePage; + public String BookPath; + + + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/BookInfo.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/BookInfo.java new file mode 100644 index 0000000..c07d140 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/BookInfo.java @@ -0,0 +1,21 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import android.graphics.Bitmap; + +import java.util.ArrayList; + +/** + * Created by manan on 3/10/17. + */ + +public class BookInfo { + public ArrayList ligatures = new ArrayList(); + public int zoomSize = 1; + public ArrayList pagedOffsets = new ArrayList(); + public int maxLigaturesInLine =0; + public int maxLinesInPage = 0; + public int margin = 5; + + +} + diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/EpubBook.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/EpubBook.java new file mode 100755 index 0000000..a839752 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/EpubBook.java @@ -0,0 +1,35 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import android.content.res.AssetManager; +import android.graphics.BitmapFactory; +import android.graphics.drawable.Drawable; + + +import java.io.FileInputStream; + +import nl.siegmann.epublib.epub.EpubReader; + +/** + * Created by manan on 3/7/17. + */ + +public class EpubBook extends Book { + EpubReader epubReader = new EpubReader(); + + public EpubBook(String path) + { + this.BookPath = path; + try + { + nl.siegmann.epublib.domain.Book book = epubReader.readEpub(new FileInputStream(BookPath)); + + this.BookTittle = book.getTitle(); + this.BookTittlePage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream()); + } + catch (Exception ex) + { + + } + + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Magazine.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Magazine.java new file mode 100644 index 0000000..d957716 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/Magazine.java @@ -0,0 +1,47 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +/** + * Created by manan on 3/9/17. + */ + +public class Magazine { + public int _id; + public String imageResId; + public String titleResId; + public int editorId; + + public Magazine(){ + } + + public int get_id() { + return _id; + } + + public void set_id(int _id) { + this._id = _id; + } + + public String getImageResId() { + return imageResId; + } + + public void setImageResId(String imageResId) { + this.imageResId = imageResId; + } + + public String getTitleResId() { + return titleResId; + } + + public void setTitleResId(String titleResId) { + this.titleResId = titleResId; + } + + public int getEditorId() { + return editorId; + } + + public void setEditorId(int editorId) { + this.editorId = editorId; + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageInfo.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageInfo.java new file mode 100644 index 0000000..3e14a9d --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageInfo.java @@ -0,0 +1,22 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import android.widget.ImageView; + +import java.util.ArrayList; + +/** + * Created by manan on 3/10/17. + */ + +public class PageInfo { + public ArrayList line = new ArrayList(); + public ImageView lastRenderedLigature = null; + public ImageView previousLineFirstRenderedLigature = null; + public int totalRenderedPages = 0; + public int pageHeight =0; + public int pageWidth = 0; + public PageOffset pageOffset = new PageOffset(); + public int oldDistance = 0; + + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageOffset.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageOffset.java new file mode 100644 index 0000000..3ea30fb --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/PageOffset.java @@ -0,0 +1,15 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import java.util.Stack; + +/** + * Created by manan on 3/10/17. + */ + +public class PageOffset { + public int pageNumber = 0; + public int startingLigatureIndex = 0; + public int endingLigatureIndex = 0; + public Stack pageLigaturesCount = new Stack(); + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/SegmentedBook.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/SegmentedBook.java new file mode 100755 index 0000000..e167dce --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/SegmentedBook.java @@ -0,0 +1,37 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.Drawable; +import android.util.Base64; + +import com.example.manan.enhancedurdureader.R; + +import java.io.File; +import java.nio.charset.Charset; + +/** + * Created by manan on 3/7/17. + */ + +public class SegmentedBook extends Book { + + public SegmentedBook(String path) + { + this.BookPath = path; + + File bookFile = new File(BookPath); + + this.BookTittle = bookFile.getName(); + + } + + Bitmap ConvertStringToBitmap(String Tittle) + { + byte[] encodeByte = Tittle.getBytes(Charset.forName("UTF-8")); + + Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,encodeByte.length); + return bitmap; + + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/User.java b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/User.java new file mode 100644 index 0000000..8b85396 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/ApplicationEntities/User.java @@ -0,0 +1,16 @@ +package com.example.manan.enhancedurdureader.ApplicationEntities; + +import java.util.ArrayList; + +/** + * Created by manan on 3/9/17. + */ + +public class User { + + public String userName; + public String userEmail; + public int userPicture; + public int userId; + public ArrayList
articles; +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/CustomViewPager.java b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/CustomViewPager.java new file mode 100755 index 0000000..bb2ae4c --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/CustomViewPager.java @@ -0,0 +1,34 @@ +package com.example.manan.enhancedurdureader.CustomViews; + +import android.content.Context; +import android.support.v4.view.ViewPager; +import android.util.AttributeSet; +import android.view.MotionEvent; + +/** + * Created by manan on 3/7/17. + */ + +public class CustomViewPager extends ViewPager { + private boolean swipeable = true; + + public CustomViewPager(Context context) { + super(context); + } + + public CustomViewPager(Context context, AttributeSet attrs) { + super(context, attrs); + } + + // Call this method in your motion events when you want to disable or enable + // It should work as desired. + public void setSwipeable(boolean swipeable) { + this.swipeable = swipeable; + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent arg0) { + return (this.swipeable) ? super.onInterceptTouchEvent(arg0) : false; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqEditText.java b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqEditText.java new file mode 100644 index 0000000..0adc105 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqEditText.java @@ -0,0 +1,35 @@ +package com.example.manan.enhancedurdureader.CustomViews; + +import android.content.Context; +import android.graphics.Typeface; +import android.util.AttributeSet; +import android.widget.EditText; + +/** + * Created by manan on 3/9/17. + */ + +public class NastaleeqEditText extends EditText { + public NastaleeqEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + public NastaleeqEditText(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public NastaleeqEditText(Context context) { + super(context); + init(); + } + + private void init() { + if (!isInEditMode()) { + Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/nastaleeq.ttf"); + setTypeface(tf); + } + } +} + diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqTextView.java b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqTextView.java new file mode 100644 index 0000000..f9f9c97 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/CustomViews/NastaleeqTextView.java @@ -0,0 +1,35 @@ +package com.example.manan.enhancedurdureader.CustomViews; + +import android.content.Context; +import android.graphics.Typeface; +import android.util.AttributeSet; +import android.widget.TextView; + +/** + * Created by manan on 3/9/17. + */ + +public class NastaleeqTextView extends TextView { + + public NastaleeqTextView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + public NastaleeqTextView(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public NastaleeqTextView(Context context) { + super(context); + init(); + } + + private void init() { + + Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/nastaleeq.ttf"); + setTypeface(tf); + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/DataStorage/LocalStorage.java b/app/src/main/java/com/example/manan/enhancedurdureader/DataStorage/LocalStorage.java new file mode 100644 index 0000000..cb70c47 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/DataStorage/LocalStorage.java @@ -0,0 +1,457 @@ +package com.example.manan.enhancedurdureader.DataStorage; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteException; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + + +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.ArticleVote; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; + +import java.util.ArrayList; + +import static android.content.ContentValues.TAG; + +/** + * Created by Anas - Plumlogix on 2/5/2017. + */ + +public class LocalStorage extends SQLiteOpenHelper { + + + public static final int DATABASE_VERSION = 1; + public static final String DATABASE_NAME = "risala.db"; + public static final String DATABASE_TABLE_ARTICLES = "Articles"; + public static final String ARTICLE_COLUMN_ID = "id"; + public static final String ARTICLE_COLUMN_TITLE = "title"; + public static final String ARTICLE_COLUMN_BODY = "body"; + public static final String ARTICLE_COLUMN_COVER_PATH = "coverPath"; + public static final String ARTICLE_COLUMN_MAGZINE_ID = "magzineId"; + public static final String ARTICLE_COLUMN_AUTHOR_ID = "authorId"; + + public static final String DATABASE_TABLE_MAGZINES = "Magzines"; + public static final String MAGZINE_COLUMN_ID = "id"; + public static final String MAGZINE_COLUMN_NAME = "name"; + public static final String MAGZINE_COLUMN_COVER_PATH = "coverPath"; + public static final String MAGZINE_COLUMN_EDITOR_ID = "editorId"; + + public static final String DATABASE_TABLE_VOTES="ArticleVotes"; + public static final String VOTES_ID = "id"; + public static final String VOTES_VALUE = "value"; + public static final String VOTES_ARTICLE = "articleId"; + public static final String VOTES_MAGZINE = "magzineId"; + public static final String VOTES_USER = "userId"; + + + @Override + public void onCreate(SQLiteDatabase db) { + + String query = "Create Table "+ DATABASE_TABLE_MAGZINES +" ("+ + MAGZINE_COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ + MAGZINE_COLUMN_NAME+" TEXT, "+ + MAGZINE_COLUMN_COVER_PATH+" TEXT, "+ + MAGZINE_COLUMN_EDITOR_ID+ " INTEGER );"; + + db.execSQL(query); + + query = "Create Table "+ DATABASE_TABLE_ARTICLES +" ("+ + ARTICLE_COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ + ARTICLE_COLUMN_TITLE+" TEXT, "+ + ARTICLE_COLUMN_BODY+" TEXT, "+ + ARTICLE_COLUMN_COVER_PATH+" TEXT, "+ + ARTICLE_COLUMN_AUTHOR_ID+ " INTEGER, "+ + ARTICLE_COLUMN_MAGZINE_ID+" INTEGER );"; + + db.execSQL(query); + + query = "Create Table "+ DATABASE_TABLE_VOTES +" ("+ + VOTES_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ + VOTES_VALUE+" TEXT, "+ + VOTES_MAGZINE+" TEXT, "+ + VOTES_ARTICLE+ " TEXT, "+ + VOTES_USER+" TEXT );"; + db.execSQL(query); + + //Insert Default Magzines + ContentValues c = new ContentValues(); + c.put(MAGZINE_COLUMN_NAME, "Saved Articles"); + + try{ + + Log.w("name", MAGZINE_COLUMN_NAME); + Log.w("cover", MAGZINE_COLUMN_COVER_PATH); + db.insert(DATABASE_TABLE_MAGZINES, null,c); + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + c = new ContentValues(); + c.put(MAGZINE_COLUMN_NAME, "All Articles"); + + try{ + + Log.w("name", MAGZINE_COLUMN_NAME); + Log.w("cover", MAGZINE_COLUMN_COVER_PATH); + db.insert(DATABASE_TABLE_MAGZINES, null,c); + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + + // Logs that the database is being upgraded + Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + + newVersion + ", which will destroy all old data"); + + // Kills the table and existing data + db.execSQL("DROP TABLE IF EXISTS Magzines"); + + // Logs that the database is being upgraded + Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + + newVersion + ", which will destroy all old data"); + + // Kills the table and existing data + db.execSQL("DROP TABLE IF EXISTS Articles"); + + // Recreates the database with a new version + // Recreates the database with a new version + + db.execSQL("DROP TABLE IF EXISTS ArticleVotes"); + onCreate(db); + } + + public void insertVote(ArticleVote vote){ + + ContentValues c = new ContentValues(); + c.put(VOTES_VALUE, String.valueOf(vote.getValue())); + c.put(VOTES_ARTICLE, String.valueOf(vote.getArticle())); + c.put(VOTES_MAGZINE, String.valueOf(vote.getMagzine())); + c.put(VOTES_USER, String.valueOf(vote.getUser())); + + + SQLiteDatabase db = getWritableDatabase(); + + try{ + + + db.insert(DATABASE_TABLE_VOTES, null,c); + + String query = "Select id from " + DATABASE_TABLE_VOTES+" where "+VOTES_ARTICLE+" = 1 and "+VOTES_VALUE+" = 1 and "+VOTES_MAGZINE+" = 3"; + Cursor cr = db.rawQuery(query, null); + cr.moveToFirst(); + + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + } + public int getAllUpvotes(Integer articleId, Integer magzineId){ + + int totalUpvotes = 0; + SQLiteDatabase db = getReadableDatabase(); + + String query = "Select * from " + DATABASE_TABLE_VOTES+" where "+VOTES_ARTICLE+" = "+articleId.toString()+" and "+VOTES_VALUE+" = 1 and "+VOTES_MAGZINE+" = "+magzineId.toString(); + Cursor c = db.rawQuery(query, null); + c.moveToFirst(); + + totalUpvotes += c.getCount(); + + c.close(); + db.close(); + + return totalUpvotes; + + } + + public boolean deleteVote(Integer userId, Integer articleId, Integer magzineId, Integer voteValue) { + + SQLiteDatabase db = getWritableDatabase(); + String query = "Delete from " + DATABASE_TABLE_VOTES+" where "+VOTES_ARTICLE+" = "+articleId.toString()+" and "+VOTES_VALUE+" = "+voteValue.toString()+" and "+VOTES_MAGZINE+" = "+magzineId.toString()+" and "+VOTES_USER+" = "+userId.toString(); + int rows = 0; + try { + + + rows = db.delete(DATABASE_TABLE_VOTES, VOTES_ARTICLE+" =?"+" and "+VOTES_VALUE+" =?"+" and "+VOTES_MAGZINE+" =?"+" and "+VOTES_USER+" =?", new String[]{articleId.toString(), voteValue.toString(), magzineId.toString(), userId.toString()} ); + // Cursor cr = db.rawQuery(query, null); + + } catch (SQLException e) { + Log.w("Deletion Vote Error ", e.getMessage()); + + } + if(rows > 0) + return true; + else + return false; + } + public boolean alreadyCastedVote(Integer userId, Integer articleId, Integer magzineId, Integer voteValue) { + + SQLiteDatabase db = getReadableDatabase(); + String query = "Select * from " + DATABASE_TABLE_VOTES+" where "+VOTES_ARTICLE+" = "+articleId.toString()+" and "+VOTES_VALUE+" = "+voteValue.toString()+" and "+VOTES_MAGZINE+" = "+magzineId.toString()+" and "+VOTES_USER+" = "+userId.toString(); + Cursor c = db.rawQuery(query, null); + c.moveToFirst(); + + if(c.getCount() == 0) + return false; + else if (c.getCount() > 0) + return true; + else + return true; + } + + public int getAllDownvotes(Integer articleId, Integer magzineId){ + + int totalDownvotes = 0; + SQLiteDatabase db = getReadableDatabase(); + + String query = "Select * from " + DATABASE_TABLE_VOTES+" where "+VOTES_ARTICLE+" = "+articleId.toString()+" and "+VOTES_VALUE+" = -1 and "+VOTES_MAGZINE+" = "+magzineId.toString(); + Cursor c = db.rawQuery(query, null); + c.moveToFirst(); + + totalDownvotes += c.getCount(); + + c.close(); + db.close(); + + return totalDownvotes; + + } + + public void insertMagzine(Magazine magzine){ + + ContentValues c = new ContentValues(); + c.put(MAGZINE_COLUMN_NAME, magzine.getTitleResId()); + c.put(MAGZINE_COLUMN_COVER_PATH, magzine.getImageResId()); + //c.put(MAGZINE_COLUMN_EDITOR_ID, magzine.getEditorId()); + + + SQLiteDatabase db = getWritableDatabase(); + + try{ + + Log.w("name", MAGZINE_COLUMN_NAME); + Log.w("cover", MAGZINE_COLUMN_COVER_PATH); + db.insert(DATABASE_TABLE_MAGZINES, null,c); + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + } + public void deleteMagzine(Integer id){ + + SQLiteDatabase db = getWritableDatabase(); + db.execSQL("delete from "+DATABASE_TABLE_MAGZINES+" where id ="+id.toString()); + + } + public Magazine getMagzine(Integer magzineId) { + + SQLiteDatabase db = getReadableDatabase(); + + String query = "Select * from " + DATABASE_TABLE_MAGZINES+" where id = "+magzineId.toString()+""; + Cursor c = db.rawQuery(query, null); + c.moveToFirst(); + Magazine magzine = null; + if (!c.isAfterLast()){ + magzine= new Magazine(); + magzine.set_id(c.getInt(c.getColumnIndex("id"))); + magzine.setTitleResId(c.getString(c.getColumnIndex("name"))); + magzine.setImageResId(c.getString(c.getColumnIndex("coverPath"))); + //magzine.setEditorId(c.getInt(c.getColumnIndex("editorId"))); + + } + c.close(); + db.close(); + + return magzine; + } + public ArrayList getAllMagzines() { + + ArrayList magzines = new ArrayList(); + + SQLiteDatabase db = getReadableDatabase(); + String query = "SELECT * FROM "+DATABASE_TABLE_MAGZINES; + Cursor c = db.rawQuery(query, null); + + c.moveToFirst(); + + while (!c.isAfterLast()){ + if(c.getString(c.getColumnIndex("name"))!=null) { + Magazine magzine = new Magazine(); + magzine.set_id(c.getInt(c.getColumnIndex("id"))); + magzine.setTitleResId(c.getString(c.getColumnIndex("name"))); + magzine.setImageResId(c.getString(c.getColumnIndex("coverPath"))); + // magzine.setEditorId(c.getInt(c.getColumnIndex("editorId"))); + + + magzines.add(magzine); + + } + c.moveToNext(); + } + c.close(); + db.close(); + return magzines; + } + + public LocalStorage(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { + super(context, DATABASE_NAME, factory, DATABASE_VERSION); + + } + + public void insertArticle(Article article){ + + ContentValues c = new ContentValues(); + c.put(ARTICLE_COLUMN_TITLE, article.getArticleTitle()); + c.put(ARTICLE_COLUMN_BODY, article.getArticleBody()); + c.put(ARTICLE_COLUMN_COVER_PATH, article.getArticleCover()); + c.put(ARTICLE_COLUMN_MAGZINE_ID, article.getMagzineId()); + //c.put(ARTICLE_COLUMN_AUTHOR_ID, 1); + + SQLiteDatabase db = getWritableDatabase(); + + try{ + + db.insert(DATABASE_TABLE_ARTICLES, null,c); + // Log.w("Inserting...", String.valueOf( db.insert(DATABASE_TABLE_ARTICLES, null,c))); + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + } + public void updateArticle(Article article){ + + ContentValues c = new ContentValues(); + if(article.get_id()!=0) + c.put(ARTICLE_COLUMN_ID, article.get_id()); + + if(article.getArticleTitle()!= null && !article.getArticleTitle().isEmpty()) + c.put(ARTICLE_COLUMN_TITLE, article.getArticleTitle()); + + if(article.getArticleTitle()!= null && !article.getArticleTitle().isEmpty()) + c.put(ARTICLE_COLUMN_BODY, article.getArticleBody()); + + if(article.getArticleBody()!= null && !article.getArticleBody().isEmpty()) + c.put(ARTICLE_COLUMN_COVER_PATH, article.getArticleCover()); + if(article.getMagzineId()!= 0) + c.put(ARTICLE_COLUMN_MAGZINE_ID, article.getMagzineId()); + + if(article.getAuthorId()!=0) + c.put(ARTICLE_COLUMN_AUTHOR_ID, 1); + + SQLiteDatabase db = getWritableDatabase(); + + try{ + + //db.update(DATABASE_TABLE_ARTICLES, c, ) + int affectedRows = db.update(DATABASE_TABLE_ARTICLES, c, " id = "+article.get_id(), null); + + Log.w("Affected Rows!", String.valueOf(affectedRows)); + + } catch (SQLiteException e){ + Log.w("Exception", e.getMessage()); + } + + } + + public void deleteArticle(Integer id){ + + SQLiteDatabase db = getWritableDatabase(); + db.execSQL("delete from "+DATABASE_TABLE_ARTICLES+" where id ="+id.toString()); + + } + public Article getArticle(Integer articleId) { + Article article= new Article(); + SQLiteDatabase db = getReadableDatabase(); + + String query = "Select * from " + DATABASE_TABLE_ARTICLES+" where id = "+articleId.toString()+""; + Cursor c = db.rawQuery(query, null); + + c.moveToFirst(); + if (!c.isAfterLast()){ + article.set_id(c.getInt(c.getColumnIndex("id"))); + article.setArticleTitle(c.getString(c.getColumnIndex("title"))); + article.setArticleBody(c.getString(c.getColumnIndex("body"))); + article.setArticleCover(c.getString(c.getColumnIndex("coverPath"))); + article.setMagzineId(c.getInt(c.getColumnIndex("magzineId"))); + article.setAuthorId(c.getInt(c.getColumnIndex("authorId"))); + + } + c.close(); + db.close(); + + return article; + } + public ArrayList
getMagazineArticles(Integer magazineID) + { + ArrayList
articles = new ArrayList
(); + + SQLiteDatabase db = getReadableDatabase(); + String query = "SELECT * FROM "+DATABASE_TABLE_ARTICLES+" where magzineId = "+magazineID.toString()+""; + Cursor c = db.rawQuery(query, null); + + c.moveToFirst(); + + + while (!c.isAfterLast()){ + if(c.getString(c.getColumnIndex("title"))!=null) { + Article article = new Article(); + article.set_id(c.getInt(c.getColumnIndex("id"))); + article.setArticleTitle(c.getString(c.getColumnIndex("title"))); + article.setArticleBody(c.getString(c.getColumnIndex("body"))); + article.setArticleCover(c.getString(c.getColumnIndex("coverPath"))); + article.setMagzineId(c.getInt(c.getColumnIndex("magzineId"))); + //article.setAuthorId(c.getInt(c.getColumnIndex("authorId"))); + + articles.add(article); + + } + c.moveToNext(); + } + c.close(); + db.close(); + return articles; + } + public ArrayList
getAllArticles() { + + ArrayList
articles = new ArrayList
(); + + SQLiteDatabase db = getReadableDatabase(); + String query = "SELECT * FROM "+DATABASE_TABLE_ARTICLES; + Cursor c = db.rawQuery(query, null); + + c.moveToFirst(); + + + while (!c.isAfterLast()){ + if(c.getString(c.getColumnIndex("title"))!=null) { + Article article = new Article(); + article.set_id(c.getInt(c.getColumnIndex("id"))); + article.setArticleTitle(c.getString(c.getColumnIndex("title"))); + article.setArticleBody(c.getString(c.getColumnIndex("body"))); + article.setArticleCover(c.getString(c.getColumnIndex("coverPath"))); + article.setMagzineId(c.getInt(c.getColumnIndex("magzineId"))); + //article.setAuthorId(c.getInt(c.getColumnIndex("authorId"))); + + articles.add(article); + + } + c.moveToNext(); + } + c.close(); + db.close(); + return articles; + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/AudioView.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/AudioView.java new file mode 100755 index 0000000..8e8c6e0 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/AudioView.java @@ -0,0 +1,332 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.pm.ActivityInfo; +import android.media.MediaMetadataRetriever; +import android.media.MediaPlayer; +import android.os.Bundle; +import android.os.Handler; +import android.text.format.DateFormat; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.MeasureSpec; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.ListView; +import android.widget.SeekBar; +import android.widget.SeekBar.OnSeekBarChangeListener; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +import java.io.File; + +// Panel specialized to show a list of audio files and play the desired one +// The audio files are stored in an array of array. +// The first index indicates the different audio files, +// the second one indicates the different extensions for the same audio file +public class AudioView extends SplitPanel { + String[][] audio; + ListView list; + private MediaPlayer player; + private Button rew; + private Button playpause; + private String actuallyPlaying = null; + private SeekBar progressBar; + private Runnable update; + private Handler progressHandler; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + View v = inflater.inflate(R.layout.activity_audio_view, container, + false); + return v; + } + + @Override + public void onActivityCreated(Bundle saved) { + super.onActivityCreated(saved); + list = (ListView) getView().findViewById(R.id.audioListView); + rew = (Button) getView().findViewById(R.id.RewindButton); + playpause = (Button) getView().findViewById(R.id.PlayPauseButton); + progressBar = (SeekBar) getView().findViewById(R.id.progressBar); + progressHandler = new Handler(); + + list.setOnItemClickListener(new OnItemClickListener() { + @Override + public void onItemClick(AdapterView listView, View itemView, + int position, long itemId) { + start(position); + } + }); + + // Play or Pause Button + playpause.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (player.isPlaying()) { + player.pause(); + playpause.setText(getString(R.string.play)); + } else { + player.start(); + playpause.setText(getString(R.string.pause)); + update.run(); + } + } + }); + + // Rewind Button + rew.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + if (player != null) { + player.seekTo(0); + player.start(); + } + } + }); + + progressBar.setProgress(0); + progressBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, + boolean fromUser) { + if (fromUser && player != null) + player.seekTo(progress); + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + + } + }); + + // This runnable update the progressBar progression every 500 + // milliseconds + update = new Runnable() { + @Override + public void run() { + if (player != null) { + progressBar.setMax(player.getDuration()); + progressBar.setProgress(player.getCurrentPosition()); + } + progressHandler.postDelayed(this, 500); + } + }; + progressHandler.postDelayed(update, 500); + + setAudioList(audio); + + updateButtons(); + } + + private void updateButtons() { + if (player != null) { + playpause.setEnabled(true); + rew.setEnabled(true); + + if (player.isPlaying()) + playpause.setText(getString(R.string.pause)); + else + playpause.setText(getString(R.string.play)); + } else { + playpause.setEnabled(false); + rew.setEnabled(false); + } + } + + // Load the list of audio files + public void setAudioList(String[][] audio) { + this.audio = audio; + if (created) { + if (player != null) { + player.stop(); + player.release(); + player = null; + } + String[] songs = new String[audio.length]; + MediaMetadataRetriever retriever = new MediaMetadataRetriever(); + + for (int i = 0; i < audio.length; i++) { + // Get Title + retriever.setDataSource(audio[i][0].replace("file:///", "")); + String title = retriever + .extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); + if (title == null) + title = (new File(audio[i][0])).getName(); + + // Get Duration + String d = retriever + .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); + if (d != null) + d = (String) DateFormat + .format("mm:ss", Integer.parseInt(d)); + else + d = ""; + + songs[i] = (i + 1) + "\t-\t" + title + "\t" + d; + } + + ArrayAdapter songList = new ArrayAdapter( + getActivity(), android.R.layout.simple_list_item_1, songs); + list.setAdapter(songList); + + if (getActivity().getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { + // Portrait case: Adjust view's height depending on the number + // of files + int height = getView().findViewById(R.id.PlayerLayout) + .getHeight() + 2; + // no files: hide the view + if (songs.length == 0) + height = 0; + + View listItem; + for (int i = 0; i < songs.length; i++) { + listItem = songList.getView(i, null, list); + listItem.measure(MeasureSpec.makeMeasureSpec(0, + MeasureSpec.UNSPECIFIED), MeasureSpec + .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); + height += listItem.getMeasuredHeight(); + } + + float weight = (float) height + / ((EpubReaderActivity) getActivity()).getHeight(); + if (weight > 0.5f) + weight = 0.5f; + navigator.changeViewsSize(1 - weight); + + // 1 file: show the player only and able it + if (songs.length == 1) { + start(0); + player.pause(); + } + } else { + // Landscape case: fifty-fifty + navigator.changeViewsSize(0.5f); + } + + updateButtons(); + + } + } + + public void start(int i) { + if (i >= 0 && i < audio.length) { + int j = 0; + boolean err = true; + + if (player == null) + player = new MediaPlayer(); + + // Try to play every format of the selected audio + while (j < audio[i].length && err) + try { + player.reset(); + player.setDataSource(audio[i][j]); + player.prepare(); + player.start(); + progressBar.setMax(player.getDuration()); + rew.setEnabled(true); + playpause.setEnabled(true); + playpause.setText(getString(R.string.pause)); + actuallyPlaying = audio[i][j]; + err = false; + } catch (Exception e) { + actuallyPlaying = null; + } + if (err) { + playpause.setEnabled(false); + ((EpubReaderActivity) getActivity()) + .errorMessage(getString(R.string.error_openaudiofile)); + } + + } + } + + public void stop() { + if (player != null) { + player.stop(); + player.release(); + player = null; + } + progressHandler.removeCallbacks(update); + } + + @Override + protected void closeView() { + stop(); + super.closeView(); + } + + @Override + public void saveState(Editor editor) { + progressHandler.removeCallbacks(update); + super.saveState(editor); + + if (player != null) { + editor.putBoolean(index + "isPlaying", player.isPlaying()); + editor.putInt(index + "current", player.getCurrentPosition()); + editor.putString(index + "actualSong", actuallyPlaying); + stop(); + } + } + + @Override + public void loadState(SharedPreferences preferences) { + super.loadState(preferences); + actuallyPlaying = preferences.getString(index + "actualSong", null); + setAudioList(audio); + + if (actuallyPlaying != null) { + player = new MediaPlayer(); + player.reset(); + try { + player.setDataSource(actuallyPlaying); + player.prepare(); + if (preferences.getBoolean(index + "isPlaying", false)) + player.start(); + player.seekTo(preferences.getInt(index + "current", 0)); + } catch (Exception e) { + // TODO error message + } + } + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/BookView.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/BookView.java new file mode 100755 index 0000000..b2f586d --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/BookView.java @@ -0,0 +1,261 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.annotation.TargetApi; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.v4.view.MotionEventCompat; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.View; +import android.view.View.OnLongClickListener; +import android.view.View.OnTouchListener; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.webkit.WebViewClient; + +import com.example.manan.enhancedurdureader.R; + +// Panel specialized in visualizing EPUB pages +public class BookView extends SplitPanel { + public ViewStateEnum state = ViewStateEnum.books; + protected String viewedPage; + protected WebView view; + protected float swipeOriginX, swipeOriginY; + private ScaleGestureDetector mScaleDetector; + + float oldDist = 1f; + static final int NONE = 0; + static final int ZOOM = 1; + int mode = NONE; + boolean swipeFlag = true; + static int textSize = 120; + + private float x1, x2; + static final int MIN_DISTANCE = 150; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + View v = inflater.inflate(R.layout.activity_book_view, container, false); + return v; + } + + @TargetApi(Build.VERSION_CODES.KITKAT) + @Override + public void onActivityCreated(Bundle saved) { + super.onActivityCreated(saved); + view = (WebView) getView().findViewById(R.id.Viewport); + view.getSettings().setTextZoom(textSize); + + mScaleDetector = new ScaleGestureDetector(getActivity().getBaseContext(), new ScaleGestureDetector.OnScaleGestureListener() { + @Override + public void onScaleEnd(ScaleGestureDetector detector) { + } + @Override + public boolean onScaleBegin(ScaleGestureDetector detector) { + return true; + } + @Override + public boolean onScale(ScaleGestureDetector detector) { + //Log.w(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor()); + return false; + } + + }); + + // enable JavaScript for cool things to happen! + view.getSettings().setJavaScriptEnabled(true); + + // ----- SWIPE PAGE + view.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + + /* if (state == ViewStateEnum.books) + swipePage(v, event, 0); + //int fontSize, newFont;*/ + WebView view = (WebView) v; + + switch (event.getAction() & MotionEvent.ACTION_MASK) { + case MotionEvent.ACTION_DOWN: + x1 = event.getX(); + break; + case MotionEvent.ACTION_UP: + if(mode != ZOOM && swipeFlag) { + //if (state == ViewStateEnum.books) + //swipePage(v, event, 0); + + } + break; + case MotionEvent.ACTION_POINTER_DOWN: + oldDist = spacing(event); + if (oldDist > 10f) { + mode = ZOOM; + } + break; + case MotionEvent.ACTION_POINTER_UP: + mode = NONE; + break; + + case MotionEvent.ACTION_MOVE: + + if(mode == ZOOM) { + float newDist = spacing(event); + if (newDist > 10f) { + float scale = newDist / oldDist; + if (scale > 1) { + int currentTextSize = view.getSettings().getTextZoom(); + textSize = currentTextSize + 15; + view.getSettings().setTextZoom(textSize); + + mode = NONE; + swipeFlag = false; + } else { + int currentTextSize = view.getSettings().getTextZoom(); + textSize = currentTextSize - 15; + view.getSettings().setTextZoom(textSize); + mode = NONE; + swipeFlag = false; + } + } + } + break; + + } + return view.onTouchEvent(event); + } + + }); + + + // ----- NOTE & LINK + view.setOnLongClickListener(new OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + Message msg = new Message(); + msg.setTarget(new Handler() { + @Override + public void handleMessage(Message msg) { + super.handleMessage(msg); + String url = msg.getData().getString( + getString(R.string.url)); + + if (url != null) + navigator.setNote(url, index); + } + }); + view.requestFocusNodeHref(msg); + + return false; + } + }); + + view.setWebViewClient(new WebViewClient() { + public boolean shouldOverrideUrlLoading(WebView view, String url) { + try { + navigator.setBookPage(url, index); + } catch (Exception e) { + errorMessage(getString(R.string.error_LoadPage)); + } + return true; + } + }); + + loadPage(viewedPage); + } + + private float spacing(MotionEvent event) { + float x = event.getX(0) - event.getX(1); + float y = event.getY(0) - event.getY(1); + return (int) Math.sqrt(x * x + y * y); + } + + public void loadPage(String path) + { + viewedPage = path; + if(created) + view.loadUrl(path); + + return; + } + + // Change page + protected void swipePage(View v, MotionEvent event, int book) { + int action = MotionEventCompat.getActionMasked(event); + + switch (action) { + case (MotionEvent.ACTION_DOWN): + swipeOriginX = event.getX(); + swipeOriginY = event.getY(); + break; + + case (MotionEvent.ACTION_UP): + int quarterWidth = (int) (screenWidth * 0.25); + float diffX = swipeOriginX - event.getX(); + float diffY = swipeOriginY - event.getY(); + float absDiffX = Math.abs(diffX); + float absDiffY = Math.abs(diffY); + + if ((diffX > quarterWidth) && (absDiffX > absDiffY)) { + try { + navigator.goToNextChapter(index); + } catch (Exception e) { + errorMessage(getString(R.string.error_cannotTurnPage)); + } + } else if ((diffX < -quarterWidth) && (absDiffX > absDiffY)) { + try { + navigator.goToPrevChapter(index); + } catch (Exception e) { + errorMessage(getString(R.string.error_cannotTurnPage)); + } + } + break; + } + + } + + @Override + public void saveState(Editor editor) { + super.saveState(editor); + editor.putString("state"+index, state.name()); + editor.putString("page"+index, viewedPage); + } + + @Override + public void loadState(SharedPreferences preferences) + { + super.loadState(preferences); + loadPage(preferences.getString("page"+index, "")); + state = ViewStateEnum.valueOf(preferences.getString("state"+index, ViewStateEnum.books.name())); + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ChangeCSSMenu.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ChangeCSSMenu.java new file mode 100755 index 0000000..86734d4 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ChangeCSSMenu.java @@ -0,0 +1,430 @@ +package com.example.manan.enhancedurdureader.EpubReader; + +import android.app.AlertDialog; +import android.app.AlertDialog.Builder; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.Context; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.AdapterView; +import android.widget.Button; +import android.widget.Spinner; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +public class ChangeCSSMenu extends DialogFragment { + + protected float value = (float) 0.2; + protected Button[] buttons = new Button[5]; + protected Builder builder; + protected Spinner spinColor; + protected Spinner spinBack; + protected Spinner spinFontStyle; + protected Spinner spinAlignText; + protected Spinner spinFontSize; + protected Spinner spinLineH; + protected Button defaultButton; + protected Spinner spinLeft; + protected Spinner spinRight; + protected int colInt, backInt, fontInt, alignInt, sizeInt, heightInt, + marginLInt, marginRInt; + protected EpubReaderActivity a; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + + builder = new AlertDialog.Builder(getActivity()); + // Get the layout inflater + LayoutInflater inflater = getActivity().getLayoutInflater(); + // Inflate and set the layout for the dialog + // Pass null as the parent view because its going in the dialog layout + + a = (EpubReaderActivity) getActivity(); + View view = inflater.inflate(R.layout.change_css, null); + + final SharedPreferences preferences = a.getPreferences(Context.MODE_PRIVATE); + + spinColor = (Spinner) view.findViewById(R.id.spinnerColor); + colInt = preferences.getInt("spinColorValue", 0); + spinColor.setSelection(colInt); + + spinBack = (Spinner) view.findViewById(R.id.spinnerBack); + backInt = preferences.getInt("spinBackValue", 0); + spinBack.setSelection(backInt); + + spinFontStyle = (Spinner) view.findViewById(R.id.spinnerFontFamily); + fontInt = preferences.getInt("spinFontStyleValue", 0); + spinFontStyle.setSelection(fontInt); + + spinAlignText = (Spinner) view.findViewById(R.id.spinnerAlign); + alignInt = preferences.getInt("spinAlignTextValue", 0); + spinAlignText.setSelection(alignInt); + + spinFontSize = (Spinner) view.findViewById(R.id.spinnerFS); + sizeInt = preferences.getInt("spinFontSizeValue", 0); + spinFontSize.setSelection(sizeInt); + + spinLineH = (Spinner) view.findViewById(R.id.spinnerLH); + heightInt = preferences.getInt("spinLineHValue", 0); + spinLineH.setSelection(heightInt); + + spinLeft = (Spinner) view.findViewById(R.id.spinnerLeft); + marginLInt = preferences.getInt("spinLeftValue", 0); + spinLeft.setSelection(marginLInt); + + spinRight = (Spinner) view.findViewById(R.id.spinnerRight); + marginRInt = preferences.getInt("spinRightValue", 0); + spinRight.setSelection(marginRInt); + + defaultButton = (Button) view.findViewById(R.id.buttonDefault); + // editTextTop = (EditText) view.findViewById(R.id.editText1); + // editTextBottom = (EditText) view.findViewById(R.id.editText2); + // editTextLeft = (EditText) view.findViewById(R.id.editText3); + // editTextRight = (EditText) view.findViewById(R.id.editText4); + + builder.setTitle("Style"); + builder.setView(view); + + spinColor + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + colInt = (int) id; + switch ((int) id) { + case 0: + a.setColor(getString(R.string.black_rgb)); + break; + case 1: + a.setColor(getString(R.string.red_rgb)); + break; + case 2: + a.setColor(getString(R.string.green_rgb)); + break; + case 3: + a.setColor(getString(R.string.blue_rgb)); + break; + case 4: + a.setColor(getString(R.string.white_rgb)); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinBack.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, + int position, long id) { + backInt = (int) id; + switch ((int) id) { + case 0: + a.setBackColor(getString(R.string.white_rgb)); + break; + case 1: + a.setBackColor(getString(R.string.red_rgb)); + break; + case 2: + a.setBackColor(getString(R.string.green_rgb)); + break; + case 3: + a.setBackColor(getString(R.string.blue_rgb)); + break; + case 4: + a.setBackColor(getString(R.string.black_rgb)); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinFontStyle + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + fontInt = (int) id; + switch ((int) id) { + case 0: + a.setFontType(getString(R.string.Arial)); + break; + case 1: + a.setFontType(getString(R.string.Serif)); + break; + case 2: + a.setFontType(getString(R.string.Monospace)); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinAlignText + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + alignInt = (int) id; + switch ((int) id) { + case 0: + a.setAlign(getString(R.string.Left_Align)); + break; + case 1: + a.setAlign(getString(R.string.Center_Align)); + break; + case 2: + a.setAlign(getString(R.string.Right_Align)); + break; + case 3: + a.setAlign(getString(R.string.Justify)); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinFontSize + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + sizeInt = (int) id; + switch ((int) id) { + case 0: + a.setFontSize("100"); + break; + case 1: + a.setFontSize("125"); + break; + case 2: + a.setFontSize("150"); + break; + case 3: + a.setFontSize("175"); + break; + case 4: + a.setFontSize("200"); + break; + case 5: + a.setFontSize("90"); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinLineH + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + heightInt = (int) id; + switch ((int) id) { + case 0: + a.setLineHeight("1"); + break; + case 1: + a.setLineHeight("1.25"); + break; + case 2: + a.setLineHeight("1.5"); + break; + case 3: + a.setLineHeight("1.75"); + break; + case 4: + a.setLineHeight("2"); + break; + case 5: + a.setLineHeight("0.9"); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinLeft.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, View view, + int position, long id) { + marginLInt = (int) id; + switch ((int) id) { + case 0: + a.setMarginLeft("0"); + break; + case 1: + a.setMarginLeft("5"); + break; + case 2: + a.setMarginLeft("10"); + break; + case 3: + a.setMarginLeft("15"); + break; + case 4: + a.setMarginLeft("20"); + break; + case 5: + a.setMarginLeft("25"); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + spinRight + .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + + @Override + public void onItemSelected(AdapterView parent, + View view, int position, long id) { + marginRInt = (int) id; + switch ((int) id) { + case 0: + a.setMarginRight("0"); + break; + case 1: + a.setMarginRight("5"); + break; + case 2: + a.setMarginRight("10"); + break; + case 3: + a.setMarginRight("15"); + break; + case 4: + a.setMarginRight("20"); + break; + case 5: + a.setMarginRight("25"); + break; + default: + break; + } + } + + @Override + public void onNothingSelected(AdapterView arg0) { + + } + }); + + defaultButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + + a.setColor(""); + a.setBackColor(""); + a.setFontType(""); + a.setFontSize(""); + a.setLineHeight(""); + a.setAlign(""); + a.setMarginLeft(""); + a.setMarginRight(""); + a.setCSS(); + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("spinColorValue", 0); + editor.putInt("spinBackValue", 0); + editor.putInt("spinFontStyleValue", 0); + editor.putInt("spinAlignTextValue", 0); + editor.putInt("spinFontSizeValue", 0); + editor.putInt("spinLineHValue", 0); + editor.putInt("spinLeftValue", 0); + editor.putInt("spinRightValue", 0); + editor.commit(); + + dismiss(); + } + }); + + builder.setPositiveButton(getString(R.string.OK), + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + // a.setLineHeight(editTextLineH.getText() + // .toString()); + // a.setMargin(editTextTop.getText() + // .toString(), editTextBottom.getText() + // .toString(), editTextLeft.getText().toString(), + // editTextRight.getText().toString()); + a.setCSS(); + + SharedPreferences.Editor editor = preferences.edit(); + editor.putInt("spinColorValue", colInt); + editor.putInt("spinBackValue", backInt); + editor.putInt("spinFontStyleValue", fontInt); + editor.putInt("spinAlignTextValue", alignInt); + editor.putInt("spinFontSizeValue", sizeInt); + editor.putInt("spinLineHValue", heightInt); + editor.putInt("spinLeftValue", marginLInt); + editor.putInt("spinRightValue", marginRInt); + editor.commit(); + } + }); + builder.setNegativeButton(getString(R.string.Cancel), + new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); + + return builder.create(); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/DataView.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/DataView.java new file mode 100755 index 0000000..604226c --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/DataView.java @@ -0,0 +1,104 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.webkit.WebViewClient; + +import com.example.manan.enhancedurdureader.R; + +//Panel specialized in visualizing HTML-data +public class DataView extends SplitPanel { + protected WebView view; + protected String data; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + View v = inflater.inflate(R.layout.activity_data_view, container, false); + return v; + } + + @Override + public void onActivityCreated(Bundle saved) { + super.onActivityCreated(saved); + view = (WebView) getView().findViewById(R.id.Viewport); + + view.setWebViewClient(new WebViewClient() { + public boolean shouldOverrideUrlLoading(WebView view, String url) { + try { + navigator.setBookPage(url, index); + } catch (Exception e) { + errorMessage(getString(R.string.error_LoadPage)); + } + return true; + } + }); + + loadData(data); + } + + public void loadData(String source) + { + /*data = "\n" + + "\n" + + ""; + data+=source; + data +="";*/ + data = source; + + if(created) + view.loadData(data, getActivity().getApplicationContext().getResources().getString(R.string.textOrHTML), null); + } + + @Override + public void saveState(Editor editor) + { + super.saveState(editor); + editor.putString("data"+index, data); + } + + @Override + public void loadState(SharedPreferences preferences) + { + super.loadState(preferences); + loadData(preferences.getString("data"+index, "")); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubManipulator.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubManipulator.java new file mode 100755 index 0000000..69f7d19 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubManipulator.java @@ -0,0 +1,783 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.content.Context; +import android.os.Environment; +import android.util.Log; + +import com.example.manan.enhancedurdureader.R; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import nl.siegmann.epublib.domain.Author; +import nl.siegmann.epublib.domain.Book; +import nl.siegmann.epublib.domain.Metadata; +import nl.siegmann.epublib.domain.Spine; +import nl.siegmann.epublib.domain.SpineReference; +import nl.siegmann.epublib.domain.TOCReference; +import nl.siegmann.epublib.domain.TableOfContents; +import nl.siegmann.epublib.epub.EpubReader; + +public class EpubManipulator { + private Book book; + private int currentSpineElementIndex; + private String currentPage; + private String[] spineElementPaths; + // NOTE: currently, counting the number of XHTML pages + private int pageCount; + private int currentLanguage; + private List availableLanguages; + // tells whether a page has a translation available + private List translations; + private String decompressedFolder; + private String pathOPF; + private static Context context; + private static String location = Environment.getExternalStorageDirectory() + + "/epubtemp/"; + + private String fileName; + FileInputStream fs; + private String actualCSS = ""; + private String[][] audio; + + // book from fileName + public EpubManipulator(String fileName, String destFolder, + Context theContext) throws Exception { + + List spineElements; + List spineList; + + if (context == null) { + context = theContext; + } + + this.fs = new FileInputStream(fileName); + this.book = (new EpubReader()).readEpub(fs); + + this.fileName = fileName; + this.decompressedFolder = destFolder; + + Spine spine = book.getSpine(); + spineList = spine.getSpineReferences(); + + this.currentSpineElementIndex = 0; + this.currentLanguage = 0; + + spineElements = new ArrayList(); + pages(spineList, spineElements); + this.pageCount = spineElements.size(); + + this.spineElementPaths = new String[spineElements.size()]; + + unzip(fileName, location + decompressedFolder); + + pathOPF = getPathOPF(location + decompressedFolder); + + for (int i = 0; i < spineElements.size(); ++i) { + // TODO: is there a robust path joiner in the java libs? + this.spineElementPaths[i] = "file://" + location + + decompressedFolder + "/" + pathOPF + "/" + + spineElements.get(i); + } + + if (spineElements.size() > 0) { + goToPage(0); + } + createTocFile(); + } + + // book from already decompressed folder + public EpubManipulator(String fileName, String folder, int spineIndex, + int language, Context theContext) throws Exception { + List spineElements; + List spineList; + + if (context == null) { + context = theContext; + } + + this.fs = new FileInputStream(fileName); + this.book = (new EpubReader()).readEpub(fs); + this.fileName = fileName; + this.decompressedFolder = folder; + + Spine spine = book.getSpine(); + spineList = spine.getSpineReferences(); + this.currentSpineElementIndex = spineIndex; + this.currentLanguage = language; + spineElements = new ArrayList(); + pages(spineList, spineElements); + this.pageCount = spineElements.size(); + this.spineElementPaths = new String[spineElements.size()]; + + pathOPF = getPathOPF(location + folder); + + for (int i = 0; i < spineElements.size(); ++i) { + // TODO: is there a robust path joiner in the java libs? + this.spineElementPaths[i] = "file://" + location + folder + "/" + + pathOPF + "/" + spineElements.get(i); + } + goToPage(spineIndex); + } + + // set language from index + public void setLanguage(int lang) throws Exception { + if ((lang >= 0) && (lang <= this.availableLanguages.size())) { + this.currentLanguage = lang; + } + goToPage(this.currentSpineElementIndex); + } + + // set language from an identifier string + public void setLanguage(String lang) throws Exception { + int i = 0; + while ((i < this.availableLanguages.size()) + && (!(this.availableLanguages.get(i).equals(lang)))) { + i++; + } + setLanguage(i); + } + + // TODO: lookup table of language names from language codes + public String[] getLanguages() { + String[] lang = new String[availableLanguages.size()]; + for (int i = 0; i < availableLanguages.size(); i++) { + lang[i] = availableLanguages.get(i); + } + return lang; + } + + // create parallel text mapping + private void pages(List spineList, List pages) { + int langIndex; + String lang; + String actualPage; + + this.translations = new ArrayList(); + this.availableLanguages = new ArrayList(); + + for (int i = 0; i < spineList.size(); ++i) { + actualPage = (spineList.get(i)).getResource().getHref(); + lang = getPageLanguage(actualPage); + if (lang != "") { + // parallel text available + langIndex = languageIndexFromID(lang); + + if (langIndex == this.availableLanguages.size()) + this.availableLanguages.add(lang); + + if (langIndex == 0) { + this.translations.add(true); + pages.add(actualPage); + } + } else { + // parallel text NOT available + this.translations.add(false); + pages.add(actualPage); + } + } + } + + // language index from language string (id) + private int languageIndexFromID(String id) { + int i = 0; + while ((i < availableLanguages.size()) + && (!(availableLanguages.get(i).equals(id)))) { + i++; + } + return i; + } + + // TODO: better parsing + private static String getPathOPF(String unzipDir) throws IOException { + String pathOPF = ""; + // get the OPF path, directly from container.xml + BufferedReader br = new BufferedReader(new FileReader(unzipDir + + "/META-INF/container.xml")); + String line; + while ((line = br.readLine()) != null) { + if (line.indexOf(getS(R.string.full_path)) > -1) { + int start = line.indexOf(getS(R.string.full_path)); + int start2 = line.indexOf("\"", start); + int stop2 = line.indexOf("\"", start2 + 1); + if (start2 > -1 && stop2 > start2) { + pathOPF = line.substring(start2 + 1, stop2).trim(); + break; + } + } + } + br.close(); + + // in case the OPF file is in the root directory + if (!pathOPF.contains("/")) + pathOPF = ""; + + // remove the OPF file name and the preceding '/' + int last = pathOPF.lastIndexOf('/'); + if (last > -1) { + pathOPF = pathOPF.substring(0, last); + } + + return pathOPF; + } + + // TODO: more efficient unzipping + public void unzip(String inputZip, String destinationDirectory) + throws IOException { + int BUFFER = 2048; + List zipFiles = new ArrayList(); + File sourceZipFile = new File(inputZip); + File unzipDestinationDirectory = new File(destinationDirectory); + unzipDestinationDirectory.mkdir(); + + ZipFile zipFile; + zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); + Enumeration zipFileEntries = zipFile.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()) { + + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + File destFile = new File(unzipDestinationDirectory, currentEntry); + + if (currentEntry.endsWith(getS(R.string.zip))) { + zipFiles.add(destFile.getAbsolutePath()); + } + + File destinationParent = destFile.getParentFile(); + destinationParent.mkdirs(); + + if (!entry.isDirectory()) { + BufferedInputStream is = new BufferedInputStream( + zipFile.getInputStream(entry)); + int currentByte; + // buffer for writing file + byte data[] = new byte[BUFFER]; + + FileOutputStream fos = new FileOutputStream(destFile); + BufferedOutputStream dest = new BufferedOutputStream(fos, + BUFFER); + + while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + dest.close(); + is.close(); + + } + + } + zipFile.close(); + + for (Iterator iter = zipFiles.iterator(); iter.hasNext();) { + String zipName = (String) iter.next(); + unzip(zipName, + destinationDirectory + + File.separatorChar + + zipName.substring(0, + zipName.lastIndexOf(getS(R.string.zip)))); + } + } + + public void closeStream() throws IOException { + fs.close(); + book = null; + } + + // close the stream and delete the extraction folder + public void destroy() throws IOException { + closeStream(); + File c = new File(location + decompressedFolder); + deleteDir(c); + } + + // recursively delete a directory + private void deleteDir(File f) { + if (f.isDirectory()) + for (File child : f.listFiles()) + deleteDir(child); + f.delete(); + } + + // change the decompressedFolder name + public void changeDirName(String newName) { + File dir = new File(location + decompressedFolder); + File newDir = new File(location + newName); + dir.renameTo(newDir); + + for (int i = 0; i < spineElementPaths.length; ++i) + // TODO: is there a robust path joiner in the java libs? + spineElementPaths[i] = spineElementPaths[i].replace("file://" + + location + decompressedFolder, "file://" + location + + newName); + decompressedFolder = newName; + try { + goToPage(currentSpineElementIndex); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + // obtain a page in the current language + public String goToPage(int page) throws Exception { + return goToPage(page, this.currentLanguage); + } + + // obtain a page in the given language + public String goToPage(int page, int lang) throws Exception { + String spineElement; + String extension; + if (page < 0) { + page = 0; + } + if (page >= this.pageCount) { + page = this.pageCount - 1; + } + this.currentSpineElementIndex = page; + + spineElement = this.spineElementPaths[currentSpineElementIndex]; + + // TODO: better parsing + if (this.translations.get(page)) { + extension = spineElement.substring(spineElement.lastIndexOf(".")); + spineElement = spineElement.substring(0, + spineElement.lastIndexOf(this.availableLanguages.get(0))); + + spineElement = spineElement + this.availableLanguages.get(lang) + + extension; + } + + this.currentPage = spineElement; + + audioExtractor(currentPage); + + return spineElement; + } + + public String goToNextChapter() throws Exception { + return goToPage(this.currentSpineElementIndex + 1); + } + + public String goToPreviousChapter() throws Exception { + return goToPage(this.currentSpineElementIndex - 1); + } + + // create an HTML page with book metadata + // TODO: style it and escape metadata values + // TODO: use StringBuilder + public String metadata() { + List tmp; + Metadata metadata = book.getMetadata(); + String html = getS(R.string.htmlBodyTableOpen); + + // Titles + tmp = metadata.getTitles(); + if (tmp.size() > 0) { + html += getS(R.string.titlesMeta); + html += "" + tmp.get(0) + ""; + for (int i = 1; i < tmp.size(); i++) + html += "" + tmp.get(i) + ""; + } + + // Authors + List authors = metadata.getAuthors(); + if (authors.size() > 0) { + html += getS(R.string.authorsMeta); + html += "" + authors.get(0).getFirstname() + " " + + authors.get(0).getLastname() + ""; + for (int i = 1; i < authors.size(); i++) + html += "" + authors.get(i).getFirstname() + + " " + authors.get(i).getLastname() + ""; + } + + // Contributors + authors = metadata.getContributors(); + if (authors.size() > 0) { + html += getS(R.string.contributorsMeta); + html += "" + authors.get(0).getFirstname() + " " + + authors.get(0).getLastname() + ""; + for (int i = 1; i < authors.size(); i++) { + html += "" + authors.get(i).getFirstname() + + " " + authors.get(i).getLastname() + ""; + } + } + + // TODO: extend lib to get multiple languages? + // Language + html += getS(R.string.languageMeta) + metadata.getLanguage() + + ""; + + // Publishers + tmp = metadata.getPublishers(); + if (tmp.size() > 0) { + html += getS(R.string.publishersMeta); + html += "" + tmp.get(0) + ""; + for (int i = 1; i < tmp.size(); i++) + html += "" + tmp.get(i) + ""; + } + + // Types + tmp = metadata.getTypes(); + if (tmp.size() > 0) { + html += getS(R.string.typesMeta); + html += "" + tmp.get(0) + ""; + for (int i = 1; i < tmp.size(); i++) + html += "" + tmp.get(i) + ""; + } + + // Descriptions + tmp = metadata.getDescriptions(); + if (tmp.size() > 0) { + html += getS(R.string.descriptionsMeta); + html += "" + tmp.get(0) + ""; + for (int i = 1; i < tmp.size(); i++) + html += "" + tmp.get(i) + ""; + } + + // Rights + tmp = metadata.getRights(); + if (tmp.size() > 0) { + html += getS(R.string.rightsMeta); + html += "" + tmp.get(0) + ""; + for (int i = 1; i < tmp.size(); i++) + html += "" + tmp.get(i) + ""; + } + + html += getS(R.string.tablebodyhtmlClose); + return html; + } + + public String r_createTocFile(TOCReference e) { + + String childrenPath = "file://" + location + decompressedFolder + "/" + + pathOPF + "/" + e.getCompleteHref(); + + String html = ""; + + List children = e.getChildren(); + + for (int j = 0; j < children.size(); j++) + html += r_createTocFile(children.get(j)); + + return html; + } + + // Create an html file, which contain the TOC, in the EPUB folder + public void createTocFile() { + List tmp; + TableOfContents toc = book.getTableOfContents(); + String html = "
    "; + + tmp = toc.getTocReferences(); + + if (tmp.size() > 0) { + html += getS(R.string.tocReference); + for (int i = 0; i < tmp.size(); i++) { + String path = "file://" + location + decompressedFolder + "/" + + pathOPF + "/" + tmp.get(i).getCompleteHref(); + + html += "
  • " + "" + + tmp.get(i).getTitle() + "" + "
  • "; + + // pre-order traversal? + List children = tmp.get(i).getChildren(); + + for (int j = 0; j < children.size(); j++) + html += r_createTocFile(children.get(j)); + + } + } + + html += getS(R.string.tablebodyhtmlClose); + + // write down the html file + String filePath = location + decompressedFolder + "/Toc.html"; + try { + File file = new File(filePath); + FileWriter fw = new FileWriter(file); + fw.write(html); + fw.flush(); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + // return the path of the Toc.html file + public String tableOfContents() { + return "File://" + location + decompressedFolder + "/Toc.html"; + } + + // determine whether a book has the requested page + // if so, return its index; return -1 otherwise + public int getPageIndex(String page) { + int result = -1; + String lang; + + lang = getPageLanguage(page); + if ((this.availableLanguages.size() > 0) && (lang != "")) { + page = page.substring(0, page.lastIndexOf(lang)) + + this.availableLanguages.get(0) + + page.substring(page.lastIndexOf(".")); + } + for (int i = 0; i < this.spineElementPaths.length && result == -1; i++) { + if (page.equals(this.spineElementPaths[i])) { + result = i; + } + } + + return result; + } + + // set the current page and its language + public boolean goToPage(String page) { + int index = getPageIndex(page); + boolean res = false; + if (index >= 0) { + String newLang = getPageLanguage(page); + try { + goToPage(index); + if (newLang != "") { + setLanguage(newLang); + } + res = true; + } catch (Exception e) { + res = false; + Log.e(getS(R.string.error_goToPage), e.getMessage()); + } + } + return res; + } + + // return the language of the page according to the + // ISO 639-1 naming convention: + // foo.XX.html where X \in [a-z] + // or an empty string if language not found + public String getPageLanguage(String page) { + String[] tmp = page.split("\\."); + // Language XY is present if the string format is "pagename.XY.xhtml", + // where XY are 2 non-numeric characters that identify the language + if (tmp.length > 2) { + String secondFromLastItem = tmp[tmp.length - 2]; + if (secondFromLastItem.matches("[a-z][a-z]")) { + return secondFromLastItem; + } + } + return ""; + } + + // TODO work in progress + public void addCSS(String[] settings) { + // CSS + String css = ""; + + for (int i = 0; i < spineElementPaths.length; i++) { + String path = spineElementPaths[i].replace("file:///", ""); + String source = readPage(path); + + source = source.replace(actualCSS + "", css + ""); + + writePage(path, source); + } + actualCSS = css; + + } + + // change from relative path (that begin with ./ or ../) to absolute path + private void adjustAudioLinks() { + for (int i = 0; i < audio.length; i++) + for (int j = 0; j < audio[i].length; j++) { + if (audio[i][j].startsWith("./")) + audio[i][j] = currentPage.substring(0, + currentPage.lastIndexOf("/")) + + audio[i][j].substring(1); + + if (audio[i][j].startsWith("../")) { + String temp = currentPage.substring(0, + currentPage.lastIndexOf("/")); + audio[i][j] = temp.substring(0, temp.lastIndexOf("/")) + + audio[i][j].substring(2); + } + } + } + + // Extract all the src field of an audio tag + private ArrayList getAudioSources(String audioTag) { + ArrayList srcs = new ArrayList(); + Pattern p = Pattern.compile("src=\"[^\"]*\""); + Matcher m = p.matcher(audioTag); + while (m.find()) + srcs.add(m.group().replace("src=\"", "").replace("\"", "")); + + return srcs; + } + + // Extract all audio tags from an xhtml page + private ArrayList getAudioTags(String page) { + ArrayList res = new ArrayList(); + + String source = readPage(page); + + Pattern p = Pattern.compile("|"); + Matcher m = p.matcher(source); + while (m.find()) + res.add(m.group(0)); + + return res; + } + + private void audioExtractor(String page) { + ArrayList tags = getAudioTags(page.replace("file:///", "")); + ArrayList srcs; + audio = new String[tags.size()][]; + + for (int i = 0; i < tags.size(); i++) { + srcs = getAudioSources(tags.get(i)); + audio[i] = new String[srcs.size()]; + for (int j = 0; j < srcs.size(); j++) + audio[i][j] = srcs.get(j); + } + adjustAudioLinks(); + } + + public String[][] getAudio() { + return audio; + } + + /* + * TODO don't work properly, forse non necessario public boolean + * deleteCSS(String path) { path = path.replace("file:///", ""); String + * source = readPage(path); source = + * source.replace("", ""); + * return writePage(path, source); } + */ + + // TODO work in progress + private String readPage(String path) { + try { + FileInputStream input = new FileInputStream(path); + byte[] fileData = new byte[input.available()]; + + input.read(fileData); + input.close(); + + String xhtml = new String(fileData); + return xhtml; + } catch (IOException e) { + return ""; + } + } + + // TODO work in progress + private boolean writePage(String path, String xhtml) { + try { + File file = new File(path); + FileWriter fw = new FileWriter(file); + fw.write(xhtml); + fw.flush(); + fw.close(); + return true; + } catch (IOException e) { + return false; + } + } + + public int getCurrentSpineElementIndex() { + return currentSpineElementIndex; + } + + public String getSpineElementPath(int elementIndex) { + return spineElementPaths[elementIndex]; + } + + public String getCurrentPageURL() { + return currentPage; + } + + public int getCurrentLanguage() { + return currentLanguage; + } + + public String getFileName() { + return fileName; + } + + public String getDecompressedFolder() { + return decompressedFolder; + } + + public static String getS(int id) { + return context.getResources().getString(id); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubNavigator.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubNavigator.java new file mode 100755 index 0000000..da6665e --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/EpubNavigator.java @@ -0,0 +1,464 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.util.Log; +import android.widget.Toast; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +import java.io.IOException; + +public class EpubNavigator { + + private int nBooks; + private EpubManipulator[] books; + private SplitPanel[] views; + private boolean[] extractAudio; + private boolean synchronizedReadingActive; + private boolean parallelText = false; + private EpubReaderActivity activity; + private static Context context; + + public EpubNavigator(int numberOfBooks, EpubReaderActivity a) { + nBooks = numberOfBooks; + books = new EpubManipulator[nBooks]; + views = new SplitPanel[nBooks]; + extractAudio = new boolean[nBooks]; + activity = a; + context = a.getBaseContext(); + } + + public boolean openBook(String path, int index) { + try { + if (books[index] != null) + books[index].destroy(); + + books[index] = new EpubManipulator(path, index + "", context); + changePanel(new BookView(), index); + setBookPage(books[index].getSpineElementPath(0), index); + + return true; + } catch (Exception e) { + return false; + } + } + + public void setBookPage(String page, int index) { + + if (books[index] != null) { + books[index].goToPage(page); + if (extractAudio[index]) { + if (views[(index + 1) % nBooks] instanceof AudioView) + ((AudioView) views[(index + 1) % nBooks]) + .setAudioList(books[index].getAudio()); + else + extractAudio(index); + } + } + + loadPageIntoView(page, index); + } + + // set the page in the next panel + public void setNote(String page, int index) { + loadPageIntoView(page, (index + 1) % nBooks); + Toast.makeText(context, "page", Toast.LENGTH_LONG); + } + + public void loadPageIntoView(String pathOfPage, int index) { + ViewStateEnum state = ViewStateEnum.notes; + + if (books[index] != null) + if ((pathOfPage.equals(books[index].getCurrentPageURL())) + || (books[index].getPageIndex(pathOfPage) >= 0)) + state = ViewStateEnum.books; + + if (books[index] == null) + state = ViewStateEnum.notes; + + if (views[index] == null || !(views[index] instanceof BookView)) + changePanel(new BookView(), index); + + ((BookView) views[index]).state = state; + ((BookView) views[index]).loadPage(pathOfPage); + } + + // if synchronized reading is active, change chapter in each books + public void goToNextChapter(int book) throws Exception { + setBookPage(books[book].goToNextChapter(), book); + + if (synchronizedReadingActive) + for (int i = 1; i < nBooks; i++) + if (books[(book + i) % nBooks] != null) + setBookPage(books[(book + i) % nBooks].goToNextChapter(), + (book + i) % nBooks); + } + + // if synchronized reading is active, change chapter in each books + public void goToPrevChapter(int book) throws Exception { + setBookPage(books[book].goToPreviousChapter(), book); + + if (synchronizedReadingActive) + for (int i = 1; i < nBooks; i++) + if (books[(book + i) % nBooks] != null) + setBookPage( + books[(book + i) % nBooks].goToPreviousChapter(), + (book + i) % nBooks); + } + + public void closeView(int index) { + if (views[index] instanceof AudioView) { + ((AudioView) views[index]).stop(); + extractAudio[index > 0 ? index - 1 : nBooks - 1] = false; + } + if (extractAudio[index] + && views[(index + 1) % nBooks] instanceof AudioView) { + closeView((index + 1) % nBooks); + extractAudio[index] = false; + } + + // case: note or another panel over a book + if (books[index] != null + && (!(views[index] instanceof BookView) || (((BookView) views[index]).state != ViewStateEnum.books))) { + BookView v = new BookView(); + changePanel(v, index); + v.loadPage(books[index].getCurrentPageURL()); + } else // all other cases + { + if (books[index] != null) + try { + books[index].destroy(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + activity.removePanel(views[index]); + + while (index < nBooks - 1) { + books[index] = books[index + 1]; // shift left all books + if (books[index] != null) // updating their folder + books[index].changeDirName(index + ""); // according to the + // index + + views[index] = views[index + 1]; // shift left every panel + if (views[index] != null) { + views[index].setKey(index); // update the panel key + if (views[index] instanceof BookView + && ((BookView) views[index]).state == ViewStateEnum.books) + ((BookView) views[index]).loadPage(books[index] + .getCurrentPageURL()); // reload the book page + } + index++; + } + books[nBooks - 1] = null; // last book and last view + views[nBooks - 1] = null; // don't exist anymore + } + } + + public String[] getLanguagesBook(int index) { + return books[index].getLanguages(); + } + + public boolean parallelText(int book, int firstLanguage, int secondLanguage) { + boolean ok = true; + + if (firstLanguage != -1) { + try { + if (secondLanguage != -1) { + openBook(books[book].getFileName(), (book + 1) % 2); + books[(book + 1) % 2].goToPage(books[book] + .getCurrentSpineElementIndex()); + books[(book + 1) % 2].setLanguage(secondLanguage); + setBookPage(books[(book + 1) % 2].getCurrentPageURL(), + (book + 1) % 2); + } + books[book].setLanguage(firstLanguage); + setBookPage(books[book].getCurrentPageURL(), book); + } catch (Exception e) { + ok = false; + } + + if (ok && firstLanguage != -1 && secondLanguage != -1) + setSynchronizedReadingActive(true); + + parallelText = true; + } + return ok; + } + + public void setSynchronizedReadingActive(boolean value) { + synchronizedReadingActive = value; + } + + public boolean flipSynchronizedReadingActive() { + if (exactlyOneBookOpen()) + return false; + synchronizedReadingActive = !synchronizedReadingActive; + return true; + } + + public boolean synchronizeView(int from, int to) throws Exception { + if (!exactlyOneBookOpen()) { + setBookPage(books[to].goToPage(books[from] + .getCurrentSpineElementIndex()), to); + return true; + } else + return false; + } + + // display book metadata + // returns true if metadata are available, false otherwise + public boolean displayMetadata(int book) { + boolean res = true; + + if (books[book] != null) { + DataView dv = new DataView(); + dv.loadData(books[book].metadata()); + changePanel(dv, book); + } else + res = false; + + return res; + } + + // return true if TOC is available, false otherwise + public boolean displayTOC(int book) { + boolean res = true; + + if (books[book] != null) + setBookPage(books[book].tableOfContents(), book); + else + res = false; + return res; + } + + public void changeCSS(int book, String[] settings) { + books[book].addCSS(settings); + loadPageIntoView(books[book].getCurrentPageURL(), book); + } + + public boolean extractAudio(int book) { + if (books[book].getAudio().length > 0) { + extractAudio[book] = true; + AudioView a = new AudioView(); + a.setAudioList(books[book].getAudio()); + changePanel(a, (book + 1) % nBooks); + return true; + } + return false; + } + + public void changeViewsSize(float weight) { + if (views[0] != null && views[1] != null) { + views[0].changeWeight(1 - weight); + views[1].changeWeight(weight); + } + } + + public boolean isParallelTextOn() { + return parallelText; + } + + public boolean isSynchronized() { + return synchronizedReadingActive; + } + + public boolean atLeastOneBookOpen() { + for (int i = 0; i < nBooks; i++) + if (books[i] != null) + return true; + return false; + } + + public boolean exactlyOneBookOpen() { + int i = 0; + // find the first not null book + while (i < nBooks && books[i] == null) + i++; + + if (i == nBooks) // if every book is null + return false; // there's no opened book and return false + + i++; + + while (i < nBooks && books[i] == null) + i++; // find another not null book + + if (i == nBooks) // if there's no other not null book + return true; // there's exactly one opened book + else + // otherwise + return false; // there's more than one opened book + } + + // change the panel in position "index" with the new panel p + public void changePanel(SplitPanel p, int index) { + if (views[index] != null) { + activity.removePanelWithoutClosing(views[index]); + p.changeWeight(views[index].getWeight()); + } + + if (p.isAdded()) + activity.removePanelWithoutClosing(p); + + views[index] = p; + activity.addPanel(p); + p.setKey(index); + + for (int i = index + 1; i < views.length; i++) + if (views[i] != null) { + activity.detachPanel(views[i]); + activity.attachPanel(views[i]); + } + } + + // TODO: update when a new SplitPanel's inherited class is created + private SplitPanel newPanelByClassName(String className) { + if (className.equals(BookView.class.getName())) + return new BookView(); + if (className.equals(DataView.class.getName())) + return new DataView(); + if (className.equals(AudioView.class.getName())) + return new AudioView(); + return null; + } + + public void saveState(Editor editor) { + + editor.putBoolean(getS(R.string.sync), synchronizedReadingActive); + editor.putBoolean(getS(R.string.parallelTextBool), parallelText); + + // Save Books + for (int i = 0; i < nBooks; i++) + if (books[i] != null) { + editor.putInt(getS(R.string.CurrentPageBook) + i, + books[i].getCurrentSpineElementIndex()); + editor.putInt(getS(R.string.LanguageBook) + i, + books[i].getCurrentLanguage()); + editor.putString(getS(R.string.nameEpub) + i, + books[i].getDecompressedFolder()); + editor.putString(getS(R.string.pathBook) + i, + books[i].getFileName()); + editor.putBoolean(getS(R.string.exAudio) + i, extractAudio[i]); + try { + books[i].closeStream(); + } catch (IOException e) { + Log.e(getS(R.string.error_CannotCloseStream), + getS(R.string.Book_Stream) + (i + 1)); + e.printStackTrace(); + } + } else { + editor.putInt(getS(R.string.CurrentPageBook) + i, 0); + editor.putInt(getS(R.string.LanguageBook) + i, 0); + editor.putString(getS(R.string.nameEpub) + i, null); + editor.putString(getS(R.string.pathBook) + i, null); + } + + // Save views + for (int i = 0; i < nBooks; i++) + if (views[i] != null) { + editor.putString(getS(R.string.ViewType) + i, views[i] + .getClass().getName()); + views[i].saveState(editor); + activity.removePanelWithoutClosing(views[i]); + } else + editor.putString(getS(R.string.ViewType) + i, ""); + } + + public boolean loadState(SharedPreferences preferences) { + boolean ok = true; + synchronizedReadingActive = preferences.getBoolean(getS(R.string.sync), + false); + parallelText = preferences.getBoolean(getS(R.string.parallelTextBool), + false); + + int current, lang; + String name, path; + for (int i = 0; i < nBooks; i++) { + current = preferences.getInt(getS(R.string.CurrentPageBook) + i, 0); + lang = preferences.getInt(getS(R.string.LanguageBook) + i, 0); + name = preferences.getString(getS(R.string.nameEpub) + i, null); + path = preferences.getString(getS(R.string.pathBook) + i, null); + extractAudio[i] = preferences.getBoolean( + getS(R.string.exAudio) + i, false); + // try loading a book already extracted + if (path != null) { + try { + books[i] = new EpubManipulator(path, name, current, lang, + context); + books[i].goToPage(current); + } catch (Exception e1) { + + // exception: retry this way + try { + books[i] = new EpubManipulator(path, i + "", context); + books[i].goToPage(current); + } catch (Exception e2) { + ok = false; + } catch (Error e3) { + ok = false; + } + } catch (Error e) { + // error: retry this way + try { + books[i] = new EpubManipulator(path, i + "", context); + books[i].goToPage(current); + } catch (Exception e2) { + ok = false; + } catch (Error e3) { + ok = false; + } + } + } else + books[i] = null; + } + + return ok; + } + + public void loadViews(SharedPreferences preferences) { + for (int i = 0; i < nBooks; i++) { + views[i] = newPanelByClassName(preferences.getString( + getS(R.string.ViewType) + i, "")); + if (views[i] != null) { + activity.addPanel(views[i]); + views[i].setKey(i); + if (views[i] instanceof AudioView) + ((AudioView) views[i]).setAudioList(books[i > 0 ? i - 1 + : nBooks - 1].getAudio()); + views[i].loadState(preferences); + } + } + } + + public String getS(int id) { + return context.getResources().getString(id); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/LanguageChooser.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/LanguageChooser.java new file mode 100755 index 0000000..0840c34 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/LanguageChooser.java @@ -0,0 +1,113 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.DialogInterface; +import android.os.Bundle; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +import java.util.ArrayList; + +public class LanguageChooser extends DialogFragment { + String[] languages; + int book; + boolean[] selected; + int number_selected_elements; + ArrayList mSelectedItems = new ArrayList(); + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + Bundle b = this.getArguments(); + languages = b.getStringArray(getString(R.string.lang)); + book = b.getInt(getString(R.string.tome)); + selected = new boolean[languages.length]; + number_selected_elements = 0; + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + + builder.setTitle(getString(R.string.LanguageChooserTitle)); + builder.setMultiChoiceItems(languages, selected, + new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface dialog, int which, + boolean isChecked) { + if (isChecked) { + if (number_selected_elements == 2) { + selected[which] = false; + } else { + mSelectedItems.add(which); + number_selected_elements++; + } + } else if (mSelectedItems.contains(which)) { + mSelectedItems.remove(Integer.valueOf(which)); + number_selected_elements--; + } + } + }); + + builder.setPositiveButton(getString(R.string.OK), + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + int first = -1; + int second = -1; + + // keep the first two selected + for (int i = 0; i < selected.length; i++) { + if (selected[i]) { + if (first == -1) { + first = i; + } else if (second == -1) { + second = i; + } + } + } + + if (number_selected_elements >= 2) + ((EpubReaderActivity) getActivity()).refreshLanguages( + book, first, second); + + else if (number_selected_elements == 1) + ((EpubReaderActivity) getActivity()).refreshLanguages( + book, first, -1); + + } + }); + + builder.setNegativeButton(getString(R.string.Cancel), + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + } + }); + + return builder.create(); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SetPanelSize.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SetPanelSize.java new file mode 100755 index 0000000..3510429 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SetPanelSize.java @@ -0,0 +1,73 @@ +package com.example.manan.enhancedurdureader.EpubReader; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.Context; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.SeekBar; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +public class SetPanelSize extends DialogFragment { + + protected SeekBar seekbar; + protected float value = (float) 0.2; + protected int sBv = 50; + protected Context context; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + // Get the layout inflater + LayoutInflater inflater = getActivity().getLayoutInflater(); + // Inflate and set the layout for the dialog + // Pass null as the parent view because its going in the dialog layout + + View view = inflater.inflate(R.layout.set_panel_size, null); + + final SharedPreferences preferences = ((EpubReaderActivity) getActivity()) + .getPreferences(Context.MODE_PRIVATE); + + sBv = preferences.getInt("seekBarValue", 50); + seekbar = (SeekBar) view.findViewById(R.id.progressBar); + seekbar.setProgress(sBv); + + builder.setTitle(getString(R.string.SetSizeTitle)); + builder.setView(view); + + // (inflater.inflate(R.layout.setsize, null)) + // Add action buttons + builder.setPositiveButton(getString(R.string.OK), + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + float actual = (float) seekbar.getProgress(); + value = actual / (float) seekbar.getMax(); + if (value <= 0.1) + value = (float) 0.1; + if (value >= 0.9) + value = (float) 0.9; + + ((EpubReaderActivity) getActivity()).changeViewsSize(value); + SharedPreferences.Editor editor = preferences.edit(); + sBv = seekbar.getProgress(); + editor.putInt("seekBarValue", sBv); + editor.commit(); + } + }); + builder.setNegativeButton(getString(R.string.Cancel), + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + } + }); + return builder.create(); + } + +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SplitPanel.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SplitPanel.java new file mode 100755 index 0000000..66bbe54 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/SplitPanel.java @@ -0,0 +1,125 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + */ + +package com.example.manan.enhancedurdureader.EpubReader; + +import android.app.Fragment; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.os.Bundle; +import android.util.DisplayMetrics; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewGroup.LayoutParams; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.R; + +// Abstract fragment that represents a general panel containing only the closing button +public abstract class SplitPanel extends Fragment { + + private RelativeLayout generalLayout; + protected int index; + protected RelativeLayout layout; + protected Button closeButton; + protected EpubNavigator navigator; + protected int screenWidth; + protected int screenHeight; + protected float weight = 0.5f; // weight of the generalLayout + protected boolean created; // tells whether the fragment has been created + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + navigator = ((EpubReaderActivity) getActivity()).navigator; + View v = inflater.inflate(R.layout.activity_split_panel, container, + false); + created = false; + return v; + } + + @Override + public void onActivityCreated(Bundle saved) { + created = true; + super.onActivityCreated(saved); + generalLayout = (RelativeLayout) getView().findViewById( + R.id.GeneralLayout); + layout = (RelativeLayout) getView().findViewById(R.id.Content); + closeButton = (Button) getView().findViewById(R.id.CloseButton); + + // ----- get activity screen size + DisplayMetrics metrics = this.getResources().getDisplayMetrics(); + screenWidth = metrics.widthPixels; + screenHeight = metrics.heightPixels; + // ----- + + changeWeight(weight); + + // ----- VIEW CLOSING + closeButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + closeView(); + } + }); + } + + protected void closeView() { + navigator.closeView(index); + } + + // change the weight of the general layout + public void changeWeight(float value) { + weight = value; + if (created) { + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( + LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, value); + generalLayout.setLayoutParams(params); + } + } + + public float getWeight() { + return weight; + } + + public void setKey(int value) { + index = value; + } + + public void errorMessage(String message) { + ((EpubReaderActivity) getActivity()).errorMessage(message); + } + + public void saveState(Editor editor) { + editor.putFloat("weight" + index, weight); + } + + public void loadState(SharedPreferences preferences) { + changeWeight(preferences.getFloat("weight" + index, 0.5f)); + } +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ViewStateEnum.java b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ViewStateEnum.java new file mode 100755 index 0000000..e49ba84 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/EpubReader/ViewStateEnum.java @@ -0,0 +1,29 @@ +/* +The MIT License (MIT) + +Copyright (c) 2013, V. Giacometti, M. Giuriato, B. Petrantuono + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +package com.example.manan.enhancedurdureader.EpubReader; + +public enum ViewStateEnum { + books, notes, invisible +} diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/BooksFragment.java b/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/BooksFragment.java new file mode 100755 index 0000000..73565d0 --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/BooksFragment.java @@ -0,0 +1,142 @@ +package com.example.manan.enhancedurdureader.Fragments; + +import android.content.Intent; +import android.graphics.BitmapFactory; +import android.support.v4.app.Fragment; +import android.os.Bundle; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.AdapterView; +import android.widget.TextSwitcher; +import android.widget.TextView; +import android.widget.ViewSwitcher; + +import com.bumptech.glide.Glide; +import com.example.manan.enhancedurdureader.Activities.ArticleReadingActivity; +import com.example.manan.enhancedurdureader.Activities.EpubReaderActivity; +import com.example.manan.enhancedurdureader.Activities.SegmentedBookReaderActivity; +import com.example.manan.enhancedurdureader.Adapters.BooksAdapter; +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.Book; +import com.example.manan.enhancedurdureader.ApplicationEntities.EpubBook; +import com.example.manan.enhancedurdureader.ApplicationEntities.SegmentedBook; +import com.example.manan.enhancedurdureader.R; + +import java.io.File; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; + +import it.moondroid.coverflow.components.ui.containers.FeatureCoverFlow; + +/** + * Created by manan on 3/7/17. + */ + +public class BooksFragment extends Fragment { + + TextSwitcher mTitle; + ArrayList books = new ArrayList<>(0); + BooksAdapter booksAdapter; + FeatureCoverFlow booksCoverFlow; + View booksView; + LayoutInflater layoutInflater; + + @Override + public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { + layoutInflater = inflater; + booksView = inflater.inflate(R.layout.books_fragment,container,false); + + booksAdapter = new BooksAdapter(getContext()); + LoadBooks(); + booksAdapter.setData(books); + + booksCoverFlow = (FeatureCoverFlow) booksView.findViewById(R.id.books_coverflow); + booksCoverFlow.setAdapter(booksAdapter); + + + mTitle = (TextSwitcher) booksView.findViewById(R.id.book_title_switcher); + mTitle.setFactory(new ViewSwitcher.ViewFactory() { + @Override + public View makeView() { + TextView textView = new TextView(getActivity()); + textView.setGravity(Gravity.CENTER); + textView.setTextAppearance(getContext(),android.R.style.TextAppearance_Large); + + return textView; + } + }); + Animation in = AnimationUtils.loadAnimation(getContext(), R.anim.slide_in_top); + Animation out = AnimationUtils.loadAnimation(getContext(), R.anim.slide_out_bottom); + mTitle.setInAnimation(in); + mTitle.setOutAnimation(out); + + booksCoverFlow.setOnScrollPositionListener(new FeatureCoverFlow.OnScrollPositionListener() { + @Override + public void onScrolledToPosition(int position) { + mTitle.setText(books.get(position).BookTittle); + } + + @Override + public void onScrolling() { + mTitle.setText(""); + } + }); + booksCoverFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + Book book = (Book)booksAdapter.getItem(position%booksAdapter.getCount()); + + if(book instanceof SegmentedBook) { + Intent readActivity = new Intent(view.getContext(), SegmentedBookReaderActivity.class); + readActivity.putExtra("path", book.BookPath); + startActivity(readActivity); + } + else + { + Intent readActivity = new Intent(view.getContext(), EpubReaderActivity.class); + readActivity.putExtra("path", book.BookPath); + startActivity(readActivity); + + } + } + }); + + return booksView; + } + void LoadBooks() + { + ArrayList bookFiles = new ArrayList(); + + bookFiles = new ArrayList(Arrays.asList(new File("storage/sdcard1/EnhancedBooks/").listFiles())); + + for(File bookFile:bookFiles) + { + Book book = new Book(); + if(getFileExtension(bookFile).equalsIgnoreCase("epub")) { + book = new EpubBook(bookFile.getAbsolutePath()); + } + else + { + book = new SegmentedBook(bookFile.getAbsolutePath()); + book.BookTittlePage = BitmapFactory.decodeResource(booksView.getResources(),R.drawable.book_icon); + } + books.add(book); + } + } + + private String getFileExtension(File file) { + String name = file.getName(); + try { + return name.substring(name.lastIndexOf(".") + 1); + } catch (Exception e) { + return ""; + } + } + +} + diff --git a/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/MagazinesFragment.java b/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/MagazinesFragment.java new file mode 100755 index 0000000..d7c3c5b --- /dev/null +++ b/app/src/main/java/com/example/manan/enhancedurdureader/Fragments/MagazinesFragment.java @@ -0,0 +1,232 @@ +package com.example.manan.enhancedurdureader.Fragments; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Intent; +import android.os.AsyncTask; +import android.support.v4.app.Fragment; +import android.os.Bundle; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.AdapterView; +import android.widget.TextSwitcher; +import android.widget.TextView; +import android.widget.ViewSwitcher; + +import com.bumptech.glide.Glide; +import com.example.manan.enhancedurdureader.Activities.ArticleReadingActivity; +import com.example.manan.enhancedurdureader.Activities.SegmentedBookReaderActivity; +import com.example.manan.enhancedurdureader.Adapters.ArticleAdapter; +import com.example.manan.enhancedurdureader.Adapters.MagazineAdapter; +import com.example.manan.enhancedurdureader.ApplicationEntities.Article; +import com.example.manan.enhancedurdureader.ApplicationEntities.Magazine; +import com.example.manan.enhancedurdureader.DataStorage.LocalStorage; +import com.example.manan.enhancedurdureader.R; + +import java.util.ArrayList; + +import it.moondroid.coverflow.components.ui.containers.FeatureCoverFlow; + +/** + * Created by manan on 3/7/17. + */ + +public class MagazinesFragment extends Fragment { + View magazinesAndArticlesView; + + MagazineAdapter magazineAdapter; + ArticleAdapter articleAdapter; + + FeatureCoverFlow magazinesCoverFlow; + FeatureCoverFlow articlesCoverFlow; + + ArrayList magazines = new ArrayList(); + ArrayList
    articles = new ArrayList
    (); + + TextSwitcher magazineTextSwitcher; + TextSwitcher articleTextSwitcher; + + LocalStorage db = null; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + magazinesAndArticlesView = inflater.inflate(R.layout.magazines_fragment, container, false); + + db = new LocalStorage(getContext(), null, null, 1); + + + magazineAdapter = new MagazineAdapter(getContext()); + articleAdapter = new ArticleAdapter(getContext()); + LoadMagazines(); + LoadArticles(); + magazineAdapter.setData(magazines); + articleAdapter.setData(articles); + + magazinesCoverFlow = (FeatureCoverFlow) magazinesAndArticlesView.findViewById(R.id.magazines_coverflow); + magazinesCoverFlow.setAdapter(magazineAdapter); + + articlesCoverFlow = (FeatureCoverFlow) magazinesAndArticlesView.findViewById(R.id.articles_coverflow); + articlesCoverFlow.setAdapter(articleAdapter); + + magazineTextSwitcher = (TextSwitcher) magazinesAndArticlesView.findViewById(R.id.magazine_title_switcher); + magazineTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() { + @Override + public View makeView() { + TextView textView = new TextView(getActivity()); + textView.setGravity(Gravity.CENTER); + textView.setTextAppearance(getContext(),android.R.style.TextAppearance_Large); + + return textView; + } + }); + Animation in = AnimationUtils.loadAnimation(getContext(), R.anim.slide_in_top); + Animation out = AnimationUtils.loadAnimation(getContext(), R.anim.slide_out_bottom); + magazineTextSwitcher.setInAnimation(in); + magazineTextSwitcher.setOutAnimation(out); + + articleTextSwitcher = (TextSwitcher) magazinesAndArticlesView.findViewById(R.id.article_title_switcher); + articleTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() { + @Override + public View makeView() { + TextView textView = new TextView(getActivity()); + textView.setGravity(Gravity.CENTER); + textView.setTextAppearance(getContext(),android.R.style.TextAppearance_Large); + + return textView; + } + }); + articleTextSwitcher.setInAnimation(in); + articleTextSwitcher.setOutAnimation(out); + + magazinesCoverFlow.setOnScrollPositionListener(new FeatureCoverFlow.OnScrollPositionListener() { + @Override + public void onScrolledToPosition(int position) { + magazineTextSwitcher.setText(magazines.get(position%magazines.size()).getTitleResId()); + } + + @Override + public void onScrolling() { + magazineTextSwitcher.setText(""); + } + }); + articlesCoverFlow.setOnScrollPositionListener(new FeatureCoverFlow.OnScrollPositionListener() { + @Override + public void onScrolledToPosition(int position) { + articleTextSwitcher.setText(articles.get(position%articles.size()).getArticleTitle()); + } + @Override + public void onScrolling() { + articleTextSwitcher.setText(""); + } + }); + magazinesCoverFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + + /*ArrayList
    articles = db.getMagazineArticles(magazines.get(position%magazines.size()).get_id()); + articleAdapter = new ArticleAdapter(getContext()); + articleAdapter.setData(articles); + articlesCoverFlow.setAdapter(articleAdapter);*/ + new SetMagazineArticlesTask().execute(position%magazines.size()); + + } + }); + articlesCoverFlow.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + + Intent readActivity = new Intent(view.getContext(), ArticleReadingActivity.class); + Article a = (Article)articleAdapter.getItem(position%articleAdapter.getCount()); + readActivity.putExtra("articleId", a.get_id()); + startActivity(readActivity); + + } + }); + + return magazinesAndArticlesView; + } + + + private class SetMagazineArticlesTask extends AsyncTask { + private ProgressDialog dialog = new ProgressDialog(getContext()); + + Integer vtCount; + ArrayList
    articles; + @Override + protected String doInBackground(Integer... params) { + int position = params[0]; + int magID = magazines.get(position%magazines.size()).get_id(); + + if(magID == 1) + articles = db.getMagazineArticles(0); + else if(magID == 2) + articles = db.getAllArticles(); + else + { + articles = db.getMagazineArticles(magazines.get(position%magazines.size()).get_id()); + } + if(articles.size()>0) { + articleAdapter = new ArticleAdapter(getContext()); + articleAdapter.setData(articles); + } + return "Executed"; + } + + @Override + protected void onPostExecute(String result) { + + if (dialog.isShowing()) { + if(articles.size()>0) + articlesCoverFlow.setAdapter(articleAdapter); + dialog.dismiss(); + } + + } + + @Override + protected void onPreExecute() { + dialog.setMessage("Please Wait...."); + dialog.show(); + + } + + @Override + protected void onProgressUpdate(Void... values) {} + } + + public void UpdateMagazine() + { + LoadMagazines(); + magazineAdapter= new MagazineAdapter(getContext()); + magazineAdapter.setData(magazines); + magazinesCoverFlow.setAdapter(magazineAdapter); + + //magazineAdapter.setData(magazines); + //magazineAdapter.notifyDataSetChanged(); + //magazinesCoverFlow.setAdapter(magazineAdapter); + } + void LoadMagazines() + { + magazines = db.getAllMagzines(); + } + void LoadArticles() + { + articles = db.getAllArticles(); + if(articles.size()<=0) + { + Article art = new Article(); + art.set_id(100); + art.setArticleBody("This is our fyp"); + art.setArticleTitle("MyFYP"); + + articles.add(art); + } + } + + + +} diff --git a/app/src/main/res/anim/slide_in_top.xml b/app/src/main/res/anim/slide_in_top.xml new file mode 100755 index 0000000..e3b021f --- /dev/null +++ b/app/src/main/res/anim/slide_in_top.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/slide_out_bottom.xml b/app/src/main/res/anim/slide_out_bottom.xml new file mode 100755 index 0000000..3e64d54 --- /dev/null +++ b/app/src/main/res/anim/slide_out_bottom.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/my_fyp.jpg b/app/src/main/res/drawable-v21/my_fyp.jpg new file mode 100644 index 0000000..29fb7d2 Binary files /dev/null and b/app/src/main/res/drawable-v21/my_fyp.jpg differ diff --git a/app/src/main/res/drawable/all_articles_magazine.png b/app/src/main/res/drawable/all_articles_magazine.png new file mode 100644 index 0000000..d0304b4 Binary files /dev/null and b/app/src/main/res/drawable/all_articles_magazine.png differ diff --git a/app/src/main/res/drawable/book_icon.png b/app/src/main/res/drawable/book_icon.png new file mode 100644 index 0000000..3f130e8 Binary files /dev/null and b/app/src/main/res/drawable/book_icon.png differ diff --git a/app/src/main/res/drawable/cover_selector.xml b/app/src/main/res/drawable/cover_selector.xml new file mode 100755 index 0000000..491f58e --- /dev/null +++ b/app/src/main/res/drawable/cover_selector.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/downvote_icon.png b/app/src/main/res/drawable/downvote_icon.png new file mode 100755 index 0000000..ea78e66 Binary files /dev/null and b/app/src/main/res/drawable/downvote_icon.png differ diff --git a/app/src/main/res/drawable/image_1.jpg b/app/src/main/res/drawable/image_1.jpg new file mode 100755 index 0000000..64d6668 Binary files /dev/null and b/app/src/main/res/drawable/image_1.jpg differ diff --git a/app/src/main/res/drawable/image_2.jpg b/app/src/main/res/drawable/image_2.jpg new file mode 100755 index 0000000..ae1f193 Binary files /dev/null and b/app/src/main/res/drawable/image_2.jpg differ diff --git a/app/src/main/res/drawable/image_3.jpg b/app/src/main/res/drawable/image_3.jpg new file mode 100755 index 0000000..e7ac1f3 Binary files /dev/null and b/app/src/main/res/drawable/image_3.jpg differ diff --git a/app/src/main/res/drawable/image_4.jpg b/app/src/main/res/drawable/image_4.jpg new file mode 100755 index 0000000..2daae50 Binary files /dev/null and b/app/src/main/res/drawable/image_4.jpg differ diff --git a/app/src/main/res/drawable/image_selector.png b/app/src/main/res/drawable/image_selector.png new file mode 100755 index 0000000..9df71cf Binary files /dev/null and b/app/src/main/res/drawable/image_selector.png differ diff --git a/app/src/main/res/drawable/label_background.xml b/app/src/main/res/drawable/label_background.xml new file mode 100755 index 0000000..fd9338e --- /dev/null +++ b/app/src/main/res/drawable/label_background.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/layout_border.xml b/app/src/main/res/drawable/layout_border.xml new file mode 100755 index 0000000..5a8b11c --- /dev/null +++ b/app/src/main/res/drawable/layout_border.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/publish_icon.png b/app/src/main/res/drawable/publish_icon.png new file mode 100644 index 0000000..1575306 Binary files /dev/null and b/app/src/main/res/drawable/publish_icon.png differ diff --git a/app/src/main/res/drawable/save_icon.png b/app/src/main/res/drawable/save_icon.png new file mode 100644 index 0000000..2de9d71 Binary files /dev/null and b/app/src/main/res/drawable/save_icon.png differ diff --git a/app/src/main/res/drawable/saved_articles_magazine.png b/app/src/main/res/drawable/saved_articles_magazine.png new file mode 100644 index 0000000..62bad80 Binary files /dev/null and b/app/src/main/res/drawable/saved_articles_magazine.png differ diff --git a/app/src/main/res/drawable/side_nav_bar.xml b/app/src/main/res/drawable/side_nav_bar.xml new file mode 100755 index 0000000..458b4b0 --- /dev/null +++ b/app/src/main/res/drawable/side_nav_bar.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/upvote_icon.png b/app/src/main/res/drawable/upvote_icon.png new file mode 100755 index 0000000..e82387c Binary files /dev/null and b/app/src/main/res/drawable/upvote_icon.png differ diff --git a/app/src/main/res/drawable/user_profile.png b/app/src/main/res/drawable/user_profile.png new file mode 100755 index 0000000..30312e7 Binary files /dev/null and b/app/src/main/res/drawable/user_profile.png differ diff --git a/app/src/main/res/drawable/vote_count_badge.xml b/app/src/main/res/drawable/vote_count_badge.xml new file mode 100755 index 0000000..8588888 --- /dev/null +++ b/app/src/main/res/drawable/vote_count_badge.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-land/activity_epub_reader.xml b/app/src/main/res/layout-land/activity_epub_reader.xml new file mode 100644 index 0000000..bf6a570 --- /dev/null +++ b/app/src/main/res/layout-land/activity_epub_reader.xml @@ -0,0 +1,26 @@ + + + + + + + diff --git a/app/src/main/res/layout/activity_article_publish.xml b/app/src/main/res/layout/activity_article_publish.xml new file mode 100644 index 0000000..c25cc2c --- /dev/null +++ b/app/src/main/res/layout/activity_article_publish.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_article_reading.xml b/app/src/main/res/layout/activity_article_reading.xml new file mode 100644 index 0000000..101c699 --- /dev/null +++ b/app/src/main/res/layout/activity_article_reading.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_audio_view.xml b/app/src/main/res/layout/activity_audio_view.xml new file mode 100755 index 0000000..83ec936 --- /dev/null +++ b/app/src/main/res/layout/activity_audio_view.xml @@ -0,0 +1,102 @@ + + + + + + + + +