diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 76661df..5398909 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -29,9 +29,9 @@ jobs: "$ANDROID_HOME/build-tools/35.0.0/apksigner" verify --verbose app/build/outputs/apk/debug/app-debug.apk "$ANDROID_HOME/build-tools/35.0.0/aapt" dump permissions app/build/outputs/apk/debug/app-debug.apk | tee permissions.txt if grep -F 'android.permission.INTERNET' permissions.txt; then exit 1; fi - cp app/build/outputs/apk/debug/app-debug.apk NotenSplit-Offline.apk + cp app/build/outputs/apk/debug/app-debug.apk NotenSplit-Offline-0.2.apk - uses: actions/upload-artifact@v4 with: - name: NotenSplit-Offline-APK - path: NotenSplit-Offline.apk + name: NotenSplit-Offline-0.2-APK + path: NotenSplit-Offline-0.2.apk if-no-files-found: error diff --git a/README.md b/README.md index 1e8d934..05cb9b5 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,2 @@ -# NotenSplit Offline – Version 0.1.0 - -Eigenständiger deutschsprachiger Android-Nachbau der Grundidee von Partifi, kein offizieller Port. Keine Internetberechtigung, Werbung, Konten oder Drittanbieter-Bibliotheken zur Laufzeit. Android 5.0 (API 21) oder neuer. - -## APK -Unter Actions > Android APK den erfolgreichen Build öffnen und NotenSplit-Offline-APK herunterladen, ZIP entpacken und NotenSplit-Offline.apk installieren. Debug-signierte Testversion, nicht für den Play Store. GitHub Actions unterliegt dem Kontingent des Kontos. - -## Bedienung -1. Lokale PDF öffnen; sie wird in die private App-Ablage kopiert. -2. Trennlinien zwischen den Notensystemen verschieben, hinzufügen oder löschen. Abschnitte antippen und benennen. Gemeinsame Angaben als all, ausgelassene Abschnitte als skip benennen. -3. Stimmenfolge kann wiederkehrende Namen auf allen Seiten vergeben. Jede Seite kontrollieren. -4. Vorschau und PDF-Stimmen exportieren. A4-Raster-PDFs, kein Erhalt der Originalvektoren. -5. Projekte werden lokal gespeichert. - -## Grenzen -Die Erkennung ist heuristisch, keine OMR, keine automatische Instrumenterkennung. Keine Onlinebibliothek, Cue-Verkleinerung oder manuell steuerbaren Seitenumbrüche. Kein vollständiger Ersatz für sämtliche Partifi-Funktionen. Gerätetest noch erforderlich. Vor produktiver Nutzung mit lokalen PDFs im Flugmodus testen. - -## Build -JDK 17, Android SDK 35, Gradle 8.9. gradle :app:assembleDebug. bash tests/test.sh wiederholt die zwei synthetischen Erkennungstests. +# NotenSplit Offline 0.2 +Eigenständiger Offline-Nachbau. Version 0.2 installiert sich neben 0.1, da die ursprüngliche Debug-Signatur nicht wiederverwendbar ist. Alte Projekte bleiben in der alten App. Neu: kompakte Bedienung, Zoom, Projektlöschung mit Bestätigung, Fortschrittsanzeige, Besetzungsvorlagen, verbesserte Trennlinien, Klaviermodus, Vektor-PDFs mit A4-Anordnung und Rastermodus. Vektor-PDFs behalten gegebenenfalls ausgeblendete Originalinhalte; für vertrauliche Ausschnitte Raster verwenden. Geräteprüfung ausstehend. PDFBox-Android 2.0.27.0 (Apache 2.0), lokal eingebunden. APK in GitHub Actions herunterladen. diff --git a/app/build.gradle b/app/build.gradle index a700127..288c8bc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -2,6 +2,9 @@ plugins { id 'com.android.application' } android { namespace 'at.notensplit.offline' compileSdk 35 - defaultConfig { applicationId 'at.notensplit.offline'; minSdk 21; targetSdk 34; versionCode 1; versionName '0.1.0' } + defaultConfig { applicationId 'at.notensplit.offline.v2'; minSdk 21; targetSdk 34; versionCode 2; versionName '0.2.0' } + packaging { resources { excludes += ['META-INF/DEPENDENCIES', 'META-INF/LICENSE', 'META-INF/LICENSE.txt', 'META-INF/NOTICE', 'META-INF/NOTICE.txt'] } } compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 } } + +dependencies { implementation 'com.tom-roush:pdfbox-android:2.0.27.0' } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 0e5f5a3..894c780 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,4 +1,4 @@ - + diff --git a/app/src/main/java/at/notensplit/offline/MainActivity.java b/app/src/main/java/at/notensplit/offline/MainActivity.java index 2fd4fd1..da6f132 100644 --- a/app/src/main/java/at/notensplit/offline/MainActivity.java +++ b/app/src/main/java/at/notensplit/offline/MainActivity.java @@ -30,6 +30,14 @@ public class MainActivity extends Activity { private Button previous, next; private boolean addMode=false, busy=false; private int selected=-1; + private float zoom=1f; + private ScrollView scroll; + private HorizontalScrollView horizontal; + private ProgressDialog activeProgress; + private boolean vectorMode=true; + private int progressBase=0, progressTotal=1; + private TextView progressLabel; + private boolean pairMode=false; private static class PageData { final ArrayList cuts=new ArrayList<>(); @@ -43,23 +51,23 @@ private static class PageData { void remove(int i){if(i>=0 && i list){cuts.clear();cuts.addAll(list);names.clear();for(int i=0;i<=cuts.size();i++)names.add("");initialized=true;} } - @Override public void onCreate(Bundle b){super.onCreate(b);root=new File(getFilesDir(),"projects");root.mkdirs();buildUI();String last=getPreferences(0).getString("last","");if(!last.isEmpty()){File dir=new File(root,last);if(dir.isDirectory())try{openProject(dir);}catch(Exception e){error(e);}}} + @Override public void onCreate(Bundle b){super.onCreate(b);root=new File(getFilesDir(),"projects");root.mkdirs();com.tom_roush.pdfbox.android.PDFBoxResourceLoader.init(getApplicationContext());vectorMode=getPreferences(0).getBoolean("vector",true);pairMode=getPreferences(0).getBoolean("pairs",false);buildUI();String last=getPreferences(0).getString("last","");if(!last.isEmpty()){File dir=new File(root,last);if(dir.isDirectory())try{openProject(dir);}catch(Exception e){error(e);}}} private int dp(float v){return (int)(v*getResources().getDisplayMetrics().density+.5f);} private LinearLayout row(){LinearLayout r=new LinearLayout(this);r.setOrientation(LinearLayout.HORIZONTAL);r.setGravity(Gravity.CENTER_VERTICAL);return r;} private TextView text(String s,int size){TextView t=new TextView(this);t.setText(s);t.setTextSize(size);t.setTextColor(INK);return t;} - private Button button(LinearLayout parent,String name,Runnable action){Button b=new Button(this);b.setText(name);b.setAllCaps(false);b.setTextSize(13);b.setOnClickListener(v->{if(!busy)action.run();});parent.addView(b,new LinearLayout.LayoutParams(0,-2,1));return b;} + private Button button(LinearLayout parent,String name,Runnable action){Button b=new Button(this);b.setText(name);b.setAllCaps(false);b.setTextSize(12);b.setMinHeight(dp(38));b.setMinimumHeight(dp(38));b.setPadding(dp(3),0,dp(3),0);b.setBackgroundTintList(android.content.res.ColorStateList.valueOf(0xffe0ece9));b.setOnClickListener(v->{if(!busy)action.run();});parent.addView(b,new LinearLayout.LayoutParams(0,-2,1));return b;} private void buildUI(){ - LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);layout.setPadding(dp(10),dp(8),dp(10),dp(6));layout.setBackgroundColor(0xfff2f5f5);setContentView(layout); - TextView heading=text("NotenSplit Offline",24);heading.setTypeface(null,Typeface.BOLD);layout.addView(heading); - status=text("Partitur öffnen · Alles bleibt auf dem Gerät",13);layout.addView(status); - LinearLayout top=row();layout.addView(top);button(top,"PDF öffnen",this::pickPdf);button(top,"Projekte",this::showProjects);button(top,"Hilfe",this::help); + LinearLayout layout=new LinearLayout(this);layout.setOrientation(1);layout.setPadding(dp(8),dp(5),dp(8),dp(5));layout.setBackgroundColor(0xfff2f5f5);setContentView(layout); + TextView heading=text("NotenSplit Offline · 0.2",20);heading.setTypeface(null,Typeface.BOLD);layout.addView(heading); + status=text("Partitur öffnen · Alles bleibt auf dem Gerät",12);status.setSingleLine(true);status.setEllipsize(android.text.TextUtils.TruncateAt.MIDDLE);layout.addView(status); + LinearLayout top=row();layout.addView(top);button(top,"PDF öffnen",this::pickPdf);button(top,"Projekte",this::showProjects);button(top,"Menü",this::menu); editor=new LinearLayout(this);editor.setOrientation(1);layout.addView(editor,new LinearLayout.LayoutParams(-1,0,1)); - LinearLayout nav=row();editor.addView(nav);previous=button(nav,"‹ Seite",()->go(pageIndex-1));pageLabel=text("",14);pageLabel.setGravity(Gravity.CENTER);nav.addView(pageLabel,new LinearLayout.LayoutParams(0,-2,1));pageLabel.setOnClickListener(v->jump());next=button(nav,"Seite ›",()->go(pageIndex+1)); + LinearLayout nav=row();editor.addView(nav);previous=button(nav,"‹ Seite",()->go(pageIndex-1));pageLabel=text("",14);pageLabel.setGravity(Gravity.CENTER);nav.addView(pageLabel,new LinearLayout.LayoutParams(0,-2,1));pageLabel.setOnClickListener(v->jump());next=button(nav,"Seite ›",()->go(pageIndex+1));button(nav,"− Zoom",()->setZoom(zoom/1.3f));button(nav,"+ Zoom",()->setZoom(zoom*1.3f)); LinearLayout bar=row();editor.addView(bar);button(bar,"Erkennen",()->new AlertDialog.Builder(this).setTitle("Diese Seite neu erkennen?").setMessage("Vorhandene Trennlinien und Namen dieser Seite werden ersetzt.").setNegativeButton("Abbrechen",null).setPositiveButton("Erkennen",(d,w)->{PageData p=current();p.reset(detect(preview));selected=-1;changed();}).show());button(bar,"+ Linie",()->{addMode=!addMode;refreshHint();});button(bar,"− Linie",this::removeLine); - LinearLayout namesBar=row();editor.addView(namesBar);button(namesBar,"Stimmenfolge",this::nameSequence);button(namesBar,"Abschnitt benennen",this::rename);button(namesBar,"Leeren",()->new AlertDialog.Builder(this).setMessage("Alle Trennlinien und Namen dieser Seite löschen?").setNegativeButton("Nein",null).setPositiveButton("Ja",(d,w)->{current().reset(Collections.emptyList());selected=0;changed();}).show()); + LinearLayout namesBar=row();editor.addView(namesBar);button(namesBar,"Stimmenfolge",this::nameSequence);button(namesBar,"Stimme",this::rename);button(namesBar,"Leeren",()->new AlertDialog.Builder(this).setMessage("Alle Trennlinien und Namen dieser Seite löschen?").setNegativeButton("Nein",null).setPositiveButton("Ja",(d,w)->{current().reset(Collections.emptyList());selected=0;changed();}).show()); hint=text("",12);editor.addView(hint);refreshHint(); - ScrollView scroll=new ScrollView(this);scroll.setFillViewport(false);editor.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));score=new ScoreView();scroll.addView(score,new ScrollView.LayoutParams(-1,-2)); - LinearLayout foot=row();editor.addView(foot);button(foot,"Vorschau",this::choosePreview);button(foot,"PDF-Stimmen exportieren",this::pickFolder); + scroll=new ScrollView(this);scroll.setFillViewport(false);editor.addView(scroll,new LinearLayout.LayoutParams(-1,0,1));horizontal=new HorizontalScrollView(this);horizontal.setFillViewport(true);scroll.addView(horizontal,new ScrollView.LayoutParams(-1,-2));score=new ScoreView();horizontal.addView(score,new HorizontalScrollView.LayoutParams(-2,-2));horizontal.addOnLayoutChangeListener((v,l,t,r,b,ol,ot,or,ob)->{if(r-l!=or-ol)score.requestLayout();});progressLabel=text("",12);editor.addView(progressLabel); + LinearLayout foot=row();editor.addView(foot);button(foot,"Vorschau",this::choosePreview);button(foot,"PDF exportieren",this::pickFolder); editor.setVisibility(View.GONE); } private void refreshHint(){hint.setText(addMode?"Tippe auf die gewünschte neue Trennlinie.":"Abschnitt antippen · Linie ziehen · zweimal tippen zum Benennen");} @@ -72,34 +80,46 @@ private void buildUI(){ private PdfRenderer renderer(File dir)throws IOException {ParcelFileDescriptor fd=ParcelFileDescriptor.open(new File(dir,"score.pdf"),ParcelFileDescriptor.MODE_READ_ONLY);try{return new PdfRenderer(fd);}catch(RuntimeException e){fd.close();throw e;}} private Bitmap render(File dir,int index,int width)throws IOException {try(PdfRenderer r=renderer(dir);PdfRenderer.Page p=r.openPage(index)){return renderPage(p,width);}} private static Bitmap renderPage(PdfRenderer.Page p,int width){int h=Math.max(1,Math.round(width*(float)p.getHeight()/p.getWidth()));if((long)width*h>14000000L){double scale=Math.sqrt(14000000.0/(width*(double)h));width=Math.max(1,(int)(width*scale));h=Math.max(1,(int)(h*scale));}Bitmap b=Bitmap.createBitmap(width,h,Bitmap.Config.ARGB_8888);b.eraseColor(Color.WHITE);p.render(b,null,null,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);return b;} - private List detect(Bitmap b){if(b==null)return Collections.emptyList();int w=b.getWidth(),h=b.getHeight();int[] pix=new int[w*h];b.getPixels(pix,0,w,0,0,w,h);return StaffDetector.detect(pix,w,h);} + private List detect(Bitmap b){if(b==null)return Collections.emptyList();int w=b.getWidth(),h=b.getHeight();int[] pix=new int[w*h];b.getPixels(pix,0,w,0,0,w,h);List lines=StaffDetector.detect(pix,w,h);if(!pairMode)return lines;ArrayList result=new ArrayList<>();for(int i=1;i loaded=new TreeMap<>();JSONObject all=j.optJSONObject("pages");if(all!=null){Iterator it=all.keys();while(it.hasNext()){String k=it.next();JSONObject obj=all.getJSONObject(k);PageData p=new PageData();JSONArray cuts=obj.getJSONArray("cuts"),names=obj.getJSONArray("names");p.cuts.clear();p.names.clear();for(int i=0;i=pageCount)return;try{Bitmap b=render(project,index,1200);if(preview!=null)preview.recycle();preview=b;pageIndex=index;PageData p=current();if(!p.initialized)p.reset(detect(b));selected=-1;addMode=false;refreshHint();previous.setEnabled(index>0);next.setEnabled(index=pageCount)return;try{Bitmap b=render(project,index,1200);if(preview!=null)preview.recycle();preview=b;pageIndex=index;PageData p=current();if(!p.initialized)p.reset(detect(b));selected=-1;addMode=false;refreshHint();previous.setEnabled(index>0);next.setEnabled(index{try{go(Integer.parseInt(e.getText().toString())-1);}catch(Exception ex){error(ex);}}).setNegativeButton("Abbrechen",null).show();} - private void showProjects(){File[] dirs=root.listFiles(f->f.isDirectory()&&new File(f,"layout.json").exists());if(dirs==null||dirs.length==0){toast("Noch keine Projekte");return;}Arrays.sort(dirs,(a,b)->Long.compare(new File(b,"layout.json").lastModified(),new File(a,"layout.json").lastModified()));String[] labels=new String[dirs.length];for(int i=0;i{try{openProject(dirs[w]);}catch(Exception e){error(e);}}).setNegativeButton("Schließen",null).show();} - private void changed(){save();score.invalidate();} + private void showProjects(){File[] dirs=root.listFiles(f->f.isDirectory()&&new File(f,"layout.json").exists());if(dirs==null||dirs.length==0){toast("Noch keine Projekte");return;}Arrays.sort(dirs,(a,b)->Long.compare(new File(b,"layout.json").lastModified(),new File(a,"layout.json").lastModified()));String[] labels=new String[dirs.length];for(int i=0;inew AlertDialog.Builder(this).setTitle(labels[w]).setItems(new String[]{"Öffnen","Projekt umbenennen","Projekt löschen"},(q,k)->{if(k==0){try{openProject(dirs[w]);}catch(Exception e){error(e);}}else if(k==1)renameProject(dirs[w],labels[w]);else confirmDelete(new File[]{dirs[w]});}).show()).setNeutralButton("Alle löschen",(d,w)->confirmDelete(dirs)).setNegativeButton("Schließen",null).show();} + private void renameProject(File dir,String old){EditText e=new EditText(this);e.setSingleLine();e.setText(old);new AlertDialog.Builder(this).setTitle("Projektname").setView(e).setPositiveButton("Speichern",(d,w)->{String n=e.getText().toString().trim();if(n.isEmpty())return;try{JSONObject j=new JSONObject(readText(new File(dir,"layout.json")));j.put("title",n);writeJson(dir,j);if(dir.equals(project)){title=n;status.setText(title+" · lokal gespeichert");}}catch(Exception ex){error(ex);}}).setNegativeButton("Abbrechen",null).show();} + private void confirmDelete(File[] dirs){new AlertDialog.Builder(this).setTitle(dirs.length==1?"Projekt löschen?":"Alle lokalen Projekte löschen?").setMessage("Die internen PDF-Kopien und Bearbeitungen werden dauerhaft gelöscht. Originaldateien und bereits exportierte PDFs bleiben erhalten.").setNegativeButton("Abbrechen",null).setPositiveButton("Endgültig löschen",(d,w)->{boolean active=false;for(File f:dirs)if(f.equals(project))active=true;if(active){project=null;pages.clear();pageCount=0;selected=-1;getPreferences(0).edit().remove("last").apply();if(preview!=null){preview.recycle();preview=null;}editor.setVisibility(View.GONE);status.setText("Partitur öffnen · Alles bleibt auf dem Gerät");}runTask("Lokale Projekte werden gelöscht …",()->{int done=0;for(File f:dirs){deleteTree(f);progress(++done,dirs.length,"Projekte gelöscht");}return done;},n->toast(n+" Projekt(e) gelöscht"));}).show();} + private static void deleteTree(File f)throws IOException{File[] children=f.listFiles();if(children!=null)for(File c:children)deleteTree(c);if(f.exists()&&!f.delete())throw new IOException("Löschen fehlgeschlagen: "+f.getName());} + private void updateCoverage(){if(progressLabel==null)return;int n=0;for(PageData p:pages.values()){boolean complete=p.initialized;for(String s:p.names)if(s.isEmpty())complete=false;if(complete)n++;}progressLabel.setText("Bearbeitet: "+n+" / "+pageCount+" Seiten · Zoom "+Math.round(zoom*100)+" %");} + private void setZoom(float z){zoom=Math.max(1f,Math.min(3.5f,z));score.requestLayout();score.invalidate();updateCoverage();if(zoom==1)horizontal.scrollTo(0,0);} + private void menu(){String[] choices={"Hilfe","Erkennungsmodus: "+(pairMode?"Klavier / zwei Systeme":"Einzelne Notenzeilen"),"PDF-Qualität: "+(vectorMode?"Original (Vektor)":"Raster / sichtbare Ausschnitte"),"Besetzungsvorlagen","Seitenübersicht","Zoom zurücksetzen"};new AlertDialog.Builder(this).setTitle("Menü").setItems(choices,(d,w)->{switch(w){case 0:help();break;case 1:chooseDetection();break;case 2:chooseQuality();break;case 3:presets();break;case 4:if(project!=null)jump();break;case 5:if(project!=null)setZoom(1);break;}}).show();} + private void chooseDetection(){new AlertDialog.Builder(this).setTitle("Notensysteme erkennen").setSingleChoiceItems(new String[]{"Einzelne Notenzeilen (Chor, Orchester)","Je zwei Notenzeilen zusammen (Klavier)"},pairMode?1:0,(d,w)->{pairMode=w==1;getPreferences(0).edit().putBoolean("pairs",pairMode).apply();d.dismiss();toast("Modus gespeichert. Erkennen für bestehende Seiten erneut wählen.");}).setNegativeButton("Schließen",null).show();} + private void chooseQuality(){new AlertDialog.Builder(this).setTitle("Exportqualität").setSingleChoiceItems(new String[]{"Originalqualität (Vektoren / eingebettete Bilder)","Raster (nur sichtbare Notenausschnitte)"},vectorMode?0:1,(d,w)->{vectorMode=w==0;getPreferences(0).edit().putBoolean("vector",vectorMode).apply();d.dismiss();if(vectorMode)new AlertDialog.Builder(this).setTitle("Hinweis zur Originalqualität").setMessage("Vektor-PDFs verwenden Ausschnittmasken. Nicht sichtbare Inhalte der ursprünglichen Partitur können in der PDF technisch erhalten bleiben. Für vertrauliche Einzelstimmen den Rastermodus verwenden.").setPositiveButton("OK",null).show();}).setNegativeButton("Schließen",null).show();} + private void presets(){String raw=getPreferences(0).getString("presets","");ArrayList entries=new ArrayList<>();for(String x:raw.split("\\n"))if(!x.trim().isEmpty())entries.add(x);entries.add("Neue Besetzung speichern …");new AlertDialog.Builder(this).setTitle("Besetzungsvorlagen").setItems(entries.toArray(new String[0]),(d,w)->{if(w==entries.size()-1){EditText e=new EditText(this);e.setHint("Sopran, Alt, Tenor, Bass");new AlertDialog.Builder(this).setTitle("Neue Besetzung").setView(e).setPositiveButton("Speichern",(q,k)->{String s=e.getText().toString().trim().replace('\n',',');if(!s.isEmpty())getPreferences(0).edit().putString("presets",raw.isEmpty()?s:raw+"\n"+s).apply();}).setNegativeButton("Abbrechen",null).show();}else{String s=entries.get(w);new AlertDialog.Builder(this).setTitle(s).setItems(new String[]{"Als Stimmenfolge verwenden","Vorlage löschen"},(q,k)->{if(k==0){getPreferences(0).edit().putString("lastSequence",s).apply();if(project!=null)nameSequence();else toast("Vorlage ausgewählt. Zuerst eine PDF öffnen.");}else{entries.remove(w);entries.remove(entries.size()-1);getPreferences(0).edit().putString("presets",android.text.TextUtils.join("\n",entries)).apply();}}).show();}}).setNegativeButton("Schließen",null).show();} + + private void changed(){save();score.invalidate();updateCoverage();} private void save(){if(project==null)return;try{JSONObject j=new JSONObject(), all=new JSONObject();j.put("title",title);j.put("page",pageIndex);for(Map.Entry entry:pages.entrySet()){PageData p=entry.getValue();if(!p.initialized)continue;JSONObject x=new JSONObject();x.put("cuts",new JSONArray(p.cuts));x.put("names",new JSONArray(p.names));all.put(entry.getKey().toString(),x);}j.put("pages",all);writeJson(project,j);}catch(Exception e){error(e);}} private static void writeJson(File dir,JSONObject j)throws IOException {android.util.AtomicFile af=new android.util.AtomicFile(new File(dir,"layout.json"));FileOutputStream o=af.startWrite();try{o.write(j.toString().getBytes("UTF-8"));af.finishWrite(o);}catch(IOException e){af.failWrite(o);throw e;}} private static String readText(File f)throws IOException {android.util.AtomicFile af=new android.util.AtomicFile(f);return new String(af.readFully(),"UTF-8");} private void rename(){if(selected<0){toast("Zuerst einen Abschnitt antippen");return;}final int index=selected;PageData p=current();EditText input=new EditText(this);input.setSingleLine(true);input.setText(p.names.get(index));input.setHint("z. B. Klarinette 1, all, skip");new AlertDialog.Builder(this).setTitle("Abschnitt benennen").setView(input).setPositiveButton("Speichern",(d,w)->{p.names.set(index,input.getText().toString().trim());changed();}).setNegativeButton("Abbrechen",null).show();} private void removeLine(){PageData p=current();if(selected<0||p.cuts.isEmpty()){toast("Abschnitt neben der zu löschenden Linie antippen");return;}int idx=Math.min(selected,p.cuts.size()-1);new AlertDialog.Builder(this).setTitle("Trennlinie löschen?").setMessage("Der ausgewählte Abschnitt wird mit seinem Nachbarn verbunden.").setPositiveButton("Löschen",(d,w)->{p.remove(idx);selected=Math.min(selected,p.names.size()-1);changed();}).setNegativeButton("Abbrechen",null).show();} - private void nameSequence(){EditText input=new EditText(this);input.setHint("Flöte, Oboe, Klarinette, Fagott");input.setSingleLine(false);new AlertDialog.Builder(this).setTitle("Wiederkehrende Stimmenfolge").setMessage("Instrumente mit Komma trennen. Die Reihenfolge beginnt auf jeder Seite neu. Bereits benannte Abschnitte bleiben erhalten; 'all' und 'skip' zählen nicht mit.").setView(input).setPositiveButton("Alle Seiten",(d,w)->{List seq=new ArrayList<>();for(String s:input.getText().toString().split("[,;\\n]"))if(!s.trim().isEmpty())seq.add(s.trim());if(seq.isEmpty()){toast("Keine Namen eingegeben");return;}File dir=project;runTask("Seiten werden erkannt und benannt …",()->{TreeMap result=copyPages();try(PdfRenderer r=renderer(dir)){for(int i=0;i{pages.clear();pages.putAll(result);changed();toast("Stimmenfolge zugewiesen – bitte kontrollieren");});}).setNegativeButton("Abbrechen",null).show();} + private void nameSequence(){EditText input=new EditText(this);input.setHint("Flöte, Oboe, Klarinette, Fagott");input.setText(getPreferences(0).getString("lastSequence",""));input.setSingleLine(false);new AlertDialog.Builder(this).setTitle("Wiederkehrende Stimmenfolge").setMessage("Instrumente mit Komma trennen. Die Reihenfolge beginnt auf jeder Seite neu. Bereits benannte Abschnitte bleiben erhalten; 'all' und 'skip' zählen nicht mit.").setView(input).setPositiveButton("Alle Seiten",(d,w)->{List seq=new ArrayList<>();for(String s:input.getText().toString().split("[,;\\n]"))if(!s.trim().isEmpty())seq.add(s.trim());if(seq.isEmpty()){toast("Keine Namen eingegeben");return;}getPreferences(0).edit().putString("lastSequence",android.text.TextUtils.join(", ",seq)).apply();File dir=project;runTask("Seiten werden erkannt und benannt …",()->{TreeMap result=copyPages();try(PdfRenderer r=renderer(dir)){for(int i=0;i{pages.clear();pages.putAll(result);changed();toast("Stimmenfolge zugewiesen – bitte kontrollieren");});}).setNegativeButton("Abbrechen",null).show();} private TreeMap copyPages(){TreeMap result=new TreeMap<>();for(Map.Entry e:pages.entrySet()){PageData p=new PageData();p.cuts.addAll(e.getValue().cuts);p.names.clear();p.names.addAll(e.getValue().names);p.initialized=e.getValue().initialized;result.put(e.getKey(),p);}return result;} private static boolean common(String n){return "all".equalsIgnoreCase(n)||"alle".equalsIgnoreCase(n);} private static boolean skip(String n){return "skip".equalsIgnoreCase(n)||"auslassen".equalsIgnoreCase(n);} private LinkedHashSet parts(){LinkedHashSet s=new LinkedHashSet<>();for(PageData p:pages.values())for(String n:p.names)if(!n.isEmpty()&&!common(n)&&!skip(n))s.add(n);return s;} private boolean checkLabels(){if(parts().isEmpty()){toast("Zuerst mindestens eine Stimme benennen");return false;}return true;} - private void choosePreview(){if(!checkLabels())return;String[] names=parts().toArray(new String[0]);new AlertDialog.Builder(this).setTitle("Stimme für die Vorschau").setItems(names,(d,w)->{String n=names[w];File dir=project;TreeMap data=copyPages();runTask("Vorschau wird erstellt …",()->{File f=new File(getCacheDir(),"preview.pdf");try(OutputStream out=new FileOutputStream(f)){createPart(dir,data,n,out);}return f;},f->showPreview(f,n,0));}).show();} + private void choosePreview(){if(!checkLabels())return;String[] names=parts().toArray(new String[0]);new AlertDialog.Builder(this).setTitle("Stimme für die Vorschau").setItems(names,(d,w)->{String n=names[w];File dir=project;TreeMap data=copyPages();runTask("Vorschau wird erstellt …",()->{File f=new File(getCacheDir(),"preview.pdf");progressBase=0;progressTotal=Math.max(1,data.size());try(OutputStream out=new FileOutputStream(f)){createPart(dir,data,n,out);}return f;},f->showPreview(f,n,0));}).show();} private void showPreview(File f,String name,int index){try(PdfRenderer r=new PdfRenderer(ParcelFileDescriptor.open(f,ParcelFileDescriptor.MODE_READ_ONLY));PdfRenderer.Page p=r.openPage(index)){Bitmap b=renderPage(p,1000);int count=r.getPageCount();ImageView image=new ImageView(this);image.setImageBitmap(b);image.setAdjustViewBounds(true);ScrollView sc=new ScrollView(this);sc.addView(image);AlertDialog.Builder dialog=new AlertDialog.Builder(this).setTitle(name+" · "+(index+1)+" / "+count).setView(sc).setNegativeButton("Schließen",null);if(index>0)dialog.setNeutralButton("‹ Seite",(d,w)->showPreview(f,name,index-1));if(index+1showPreview(f,name,index+1));AlertDialog a=dialog.create();a.setOnDismissListener(d->{image.setImageDrawable(null);b.recycle();});a.show();}catch(Exception e){error(e);}} - private void export(Uri tree){final File dir=project;final TreeMap data=copyPages();final List names=new ArrayList<>(parts());final String base=title.replaceFirst("(?i)\\.pdf$","");runTask("Einzelstimmen werden erzeugt …",()->{Uri folder=DocumentsContract.buildDocumentUriUsingTree(tree,DocumentsContract.getTreeDocumentId(tree));int count=0;for(String n:names){File tmp=File.createTempFile("part-",".pdf",getCacheDir());try{try(OutputStream out=new FileOutputStream(tmp)){createPart(dir,data,n,out);}String filename=safe(base)+" - "+safe(n)+".pdf";Uri item=DocumentsContract.createDocument(getContentResolver(),folder,"application/pdf",filename);if(item==null)throw new IOException("Datei kann nicht angelegt werden: "+filename);try(InputStream in=new FileInputStream(tmp);OutputStream out=getContentResolver().openOutputStream(item)){if(out==null)throw new IOException("Ziel nicht beschreibbar");byte[] buf=new byte[65536];int len;while((len=in.read(buf))!=-1)out.write(buf,0,len);}count++;}finally{tmp.delete();}}return count;},count->new AlertDialog.Builder(this).setTitle("Export abgeschlossen").setMessage(count+" PDF-Einzelstimmen gespeichert. Nicht benannte Abschnitte wurden ausgelassen.").setPositiveButton("OK",null).show());} + private void export(Uri tree){final File dir=project;final TreeMap data=copyPages();final List names=new ArrayList<>(parts());final String base=title.replaceFirst("(?i)\\.pdf$","");runTask("Einzelstimmen werden erzeugt …",()->{Uri folder=DocumentsContract.buildDocumentUriUsingTree(tree,DocumentsContract.getTreeDocumentId(tree));int count=0;for(String n:names){progressBase=count*data.size();progressTotal=Math.max(1,names.size()*data.size());File tmp=File.createTempFile("part-",".pdf",getCacheDir());try{try(OutputStream out=new FileOutputStream(tmp)){createPart(dir,data,n,out);}String filename=safe(base)+" - "+safe(n)+".pdf";Uri item=DocumentsContract.createDocument(getContentResolver(),folder,"application/pdf",filename);if(item==null)throw new IOException("Datei kann nicht angelegt werden: "+filename);try(InputStream in=new FileInputStream(tmp);OutputStream out=getContentResolver().openOutputStream(item)){if(out==null)throw new IOException("Ziel nicht beschreibbar");byte[] buf=new byte[65536];int len;while((len=in.read(buf))!=-1)out.write(buf,0,len);}count++;progress(count*data.size(),Math.max(1,names.size()*data.size()),"Stimme "+count+" / "+names.size());}finally{tmp.delete();}}return count;},count->new AlertDialog.Builder(this).setTitle("Export abgeschlossen").setMessage(count+" PDF-Einzelstimmen gespeichert. Nicht benannte Abschnitte wurden ausgelassen.").setPositiveButton("OK",null).show());} private static String safe(String n){String s=n.replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]","_").trim();if(s.isEmpty())s="Stimme";return s.substring(0,Math.min(65,s.length()));} - private static void createPart(File dir,TreeMap data,String name,OutputStream out)throws Exception { + private void createPart(File dir,TreeMap data,String name,OutputStream out)throws Exception { + if(vectorMode){createVectorPart(dir,data,name,out);return;} + int done=0; PdfDocument doc=new PdfDocument(); PdfDocument.Page output=null; try(PdfRenderer r=new PdfRenderer(ParcelFileDescriptor.open(new File(dir,"score.pdf"),ParcelFileDescriptor.MODE_READ_ONLY))){ int num=0;float y=0;Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);paint.setColor(Color.BLACK); - for(Map.Entry en:data.entrySet()){PageData p=en.getValue();boolean useful=false;for(String n:p.names)if(name.equals(n)||common(n))useful=true;if(!useful)continue; + for(Map.Entry en:data.entrySet()){progress(progressBase+(++done),progressTotal,"Stimme "+name+" · Seite "+(en.getKey()+1));PageData p=en.getValue();boolean useful=false;for(String n:p.names)if(name.equals(n)||common(n))useful=true;if(!useful)continue; try(PdfRenderer.Page input=r.openPage(en.getKey())){Bitmap b=renderPage(input,2400);try{float scale=535f/b.getWidth();for(int k=0;k805){doc.finishPage(output);output=null;} if(output==null){output=doc.startPage(new PdfDocument.PageInfo.Builder(595,842,++num).create());Canvas c=output.getCanvas();paint.setTextSize(13);c.drawText(name,30,27,paint);paint.setTextSize(9);c.drawText(""+num,550,27,paint);y=43;} @@ -108,19 +128,61 @@ private static void createPart(File dir,TreeMap data,String na }}finally{b.recycle();}} }if(output!=null){doc.finishPage(output);output=null;}if(num==0)throw new IOException("Keine Abschnitte für "+name);doc.writeTo(out); }finally{if(output!=null)doc.finishPage(output);doc.close();} + } + private void createVectorPart(File dir,TreeMap data,String name,OutputStream out)throws Exception{ + try(com.tom_roush.pdfbox.pdmodel.PDDocument src=com.tom_roush.pdfbox.pdmodel.PDDocument.load(new File(dir,"score.pdf"),com.tom_roush.pdfbox.io.MemoryUsageSetting.setupTempFileOnly()); + com.tom_roush.pdfbox.pdmodel.PDDocument dst=new com.tom_roush.pdfbox.pdmodel.PDDocument(com.tom_roush.pdfbox.io.MemoryUsageSetting.setupTempFileOnly())){ + com.tom_roush.pdfbox.multipdf.PDFCloneUtility cloner=new com.tom_roush.pdfbox.multipdf.PDFCloneUtility(dst); + com.tom_roush.pdfbox.pdmodel.PDPageContentStream stream=null;float cursor=0;int done=0; + try{ + for(Map.Entry entry:data.entrySet()){ + progress(progressBase+(++done),progressTotal,"Stimme "+name+" · Seite "+(entry.getKey()+1)); + PageData p=entry.getValue();boolean useful=false;for(String n:p.names)if(name.equals(n)||common(n))useful=true;if(!useful)continue; + com.tom_roush.pdfbox.pdmodel.PDPage original=src.getPage(entry.getKey()); + com.tom_roush.pdfbox.pdmodel.common.PDRectangle box=original.getCropBox(); + float x0=box.getLowerLeftX(),y0=box.getLowerLeftY(),w=box.getWidth(),h=box.getHeight(); + int rot=((original.getRotation()%360)+360)%360; + float sw=(rot==90||rot==270)?h:w,sh=(rot==90||rot==270)?w:h; + if(sw<=0||sh<=0)throw new IOException("Ungültiges PDF-Seitenformat"); + com.tom_roush.pdfbox.pdmodel.graphics.form.PDFormXObject form=new com.tom_roush.pdfbox.pdmodel.graphics.form.PDFormXObject(dst); + form.setBBox(box); + if(original.getResources()!=null)form.setResources(new com.tom_roush.pdfbox.pdmodel.PDResources((com.tom_roush.pdfbox.cos.COSDictionary)cloner.cloneForNewDocument(original.getResources().getCOSObject()))); + try(InputStream in=original.getContents();OutputStream fo=form.getCOSObject().createOutputStream(com.tom_roush.pdfbox.cos.COSName.FLATE_DECODE)){byte[] buf=new byte[32768];int n;while((n=in.read(buf))!=-1)fo.write(buf,0,n);} + for(int i=0;i{T run()throws Exception;}private interface Done{void accept(T result);} - private void runTask(String message,Job job,Done done){if(busy)return;busy=true;ProgressDialog progress=new ProgressDialog(this);progress.setMessage(message);progress.setCancelable(false);progress.show();worker.execute(()->{try{T v=job.run();runOnUiThread(()->{busy=false;progress.dismiss();if(!isFinishing())done.accept(v);});}catch(Exception e){runOnUiThread(()->{busy=false;progress.dismiss();if(!isFinishing())error(e);});}});} + private void runTask(String message,Job job,Done done){if(busy)return;busy=true;ProgressDialog progress=new ProgressDialog(this);progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progress.setMax(100);progress.setIndeterminate(true);progress.setMessage(message);progress.setCancelable(false);activeProgress=progress;progress.show();worker.execute(()->{try{T v=job.run();runOnUiThread(()->{busy=false;activeProgress=null;progress.dismiss();if(!isFinishing())done.accept(v);});}catch(Exception e){runOnUiThread(()->{busy=false;activeProgress=null;progress.dismiss();if(!isFinishing())error(e);});}});} + private void progress(int completed,int total,String msg){final int value=Math.min(100,Math.max(0,Math.round(completed*100f/Math.max(1,total))));runOnUiThread(()->{if(activeProgress!=null){activeProgress.setIndeterminate(false);activeProgress.setProgress(value);activeProgress.setMessage(msg);}});} + private void toast(String s){Toast.makeText(this,s,Toast.LENGTH_LONG).show();} private void error(Exception e){new AlertDialog.Builder(this).setTitle("Fehler").setMessage(e.getMessage()==null?e.getClass().getSimpleName():e.getMessage()).setPositiveButton("OK",null).show();} private class ScoreView extends View { private final Paint p=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);private int drag=-1;private float downX,downY;private long lastTap=0;private int lastSegment=-1; ScoreView(){super(MainActivity.this);setBackgroundColor(Color.WHITE);} - @Override protected void onMeasure(int ws,int hs){int w=MeasureSpec.getSize(ws);int h=preview==null?dp(200):Math.round(w*(float)preview.getHeight()/preview.getWidth());setMeasuredDimension(w,h);} - @Override protected void onDraw(Canvas c){super.onDraw(c);if(preview==null)return;float w=getWidth(),h=getHeight();p.setColor(Color.WHITE);c.drawBitmap(preview,null,new RectF(0,0,w,h),p);PageData d=current();for(int i=0;i0?horizontal.getWidth():getResources().getDisplayMetrics().widthPixels-dp(16);int w=Math.max(1,Math.round(base*zoom));int h=preview==null?dp(200):Math.round(w*(float)preview.getHeight()/preview.getWidth());setMeasuredDimension(w,h);} + @Override protected void onDraw(Canvas c){super.onDraw(c);if(preview==null)return;float w=getWidth(),h=getHeight();p.setColor(Color.WHITE);c.drawBitmap(preview,null,new RectF(0,0,w,h),p);PageData d=current();for(int i=0;i=0)getParent().requestDisallowInterceptTouchEvent(true);return true; + case MotionEvent.ACTION_DOWN:downX=e.getX();downY=e.getY();drag=-1;if(!addMode){float best=dp(8);for(int i=0;i=0)getParent().requestDisallowInterceptTouchEvent(true);return true; case MotionEvent.ACTION_MOVE:if(drag>=0){float lo=drag==0?.008f:d.cuts.get(drag-1)+.008f,hi=drag==d.cuts.size()-1?.992f:d.cuts.get(drag+1)-.008f;d.cuts.set(drag,Math.max(lo,Math.min(hi,y)));invalidate();}return true; case MotionEvent.ACTION_UP:if(drag>=0){drag=-1;getParent().requestDisallowInterceptTouchEvent(false);changed();return true;}if(Math.abs(e.getX()-downX)>dp(12)||Math.abs(e.getY()-downY)>dp(12))return true;if(addMode){d.insert(y);addMode=false;refreshHint();selected=d.segment(y);changed();}else{selected=d.segment(y);invalidate();long now=SystemClock.uptimeMillis();if(lastSegment==selected&&now-lastTap<350){lastTap=0;rename();}else{lastTap=now;lastSegment=selected;}}performClick();return true; case MotionEvent.ACTION_CANCEL:if(drag>=0){drag=-1;changed();}getParent().requestDisallowInterceptTouchEvent(false);return true; diff --git a/app/src/main/java/at/notensplit/offline/StaffDetector.java b/app/src/main/java/at/notensplit/offline/StaffDetector.java index 57ce866..06e43ff 100644 --- a/app/src/main/java/at/notensplit/offline/StaffDetector.java +++ b/app/src/main/java/at/notensplit/offline/StaffDetector.java @@ -15,6 +15,17 @@ public static List detect(int[] pixels,int width,int height){ } List staves=new ArrayList<>(); for(int i=0;i+4=2&&gap<=height/24f;for(int k=0;k<4&®ular;k++)regular=Math.abs(lines.get(i+k+1)-lines.get(i+k)-gap)<=Math.max(1.5f,gap*.30f);if(regular){staves.add(new int[]{lines.get(i),lines.get(i+4)});i+=5;}else i++;} - List cuts=new ArrayList<>();for(int i=1;i cuts=new ArrayList<>(); + for(int i=1;i>16)&255)*3+((p>>8)&255)*6+(p&255);if(lum<1800)ink++;} + double score=ink*1.0+Math.abs(y-(a+b)/2.0)*.35; + if(score \ No newline at end of file