diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index ea78b5a..d1d4203 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -2,15 +2,8 @@ name: Android APK
on:
workflow_dispatch:
push:
- paths:
- - 'app/**'
- - 'build.gradle'
- - 'settings.gradle'
+ branches: [main]
pull_request:
- paths:
- - 'app/**'
- - 'build.gradle'
- - 'settings.gradle'
permissions:
contents: read
jobs:
@@ -22,15 +15,23 @@ jobs:
with:
distribution: temurin
java-version: '17'
- - uses: android-actions/setup-android@v3
- - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0'
+ - name: Check preinstalled Android SDK
+ run: |
+ if [ ! -f "$ANDROID_HOME/platforms/android-35/android.jar" ] || [ ! -x "$ANDROID_HOME/build-tools/35.0.0/apksigner" ]; then
+ "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-35' 'build-tools;35.0.0'
+ fi
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.9'
- run: bash tests/test.sh
- run: gradle --no-daemon :app:assembleDebug
+ - run: |
+ "$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-0.2.1.apk
- uses: actions/upload-artifact@v4
with:
- name: NotenSplit-Offline-APK
- path: app/build/outputs/apk/debug/app-debug.apk
+ name: NotenSplit-Offline-0.2.1-APK
+ path: NotenSplit-Offline-0.2.1.apk
if-no-files-found: error
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..da154f5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+**/build/
+local.properties
+.idea/
diff --git a/DESCRIPTION.txt b/DESCRIPTION.txt
new file mode 100644
index 0000000..9b16e40
--- /dev/null
+++ b/DESCRIPTION.txt
@@ -0,0 +1 @@
+Offline Android tool for splitting PDF music scores into individual parts, with smart staff detection and high-quality PDF export.
diff --git a/README.md b/README.md
index 8687e5d..3f17e6e 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,95 @@
-# NotenSplit-Offline
\ No newline at end of file
+
+
+

+
+# NotenSplit Offline
v0.2.1
+**PDF scores ➔ individual sheet music parts**
+[APK by Manuel Pollhammer 2026](https://www.pollhammer.org)
+
+
+
+
+
+
+
+
+---
+
+## 🚀 What is NotenSplit Offline?
+
+**NotenSplit Offline** is a free Android utility designed to separate PDF music scores into individual instrument or vocal parts directly on a smartphone or tablet. Inspired by the workflow of [Partifi](https://partifi.org/), it is an independent Android implementation with entirely local PDF processing, without registration, advertising or an internet permission.
+
+## 📦 Components
+
+* **NotenSplit Offline APK:** Interactive Android editor, PDF import, staff markers, part assignment, local projects and export.
+* **StaffDetector.java:** Heuristic staff and whitespace detection, including a two-staff piano mode.
+* **PDFBox-Android:** Locally bundled PDF library for vector-based extraction and original-quality output.
+* **GitHub Actions:** Automated APK compilation, staff-detection tests, signature verification and internet-permission checks.
+
+## 📝 Usage Modes
+
+1. **Manual separation:** Open a PDF, adjust red markers and assign names to the selected score sections.
+2. **Automatic staff detection:** Detect staff boundaries; choose individual staves or paired piano staves in the menu.
+3. **Recurring instrumentation:** Assign a repeated sequence of instruments or voices and save reusable presets. Use `all` for shared material or `skip` to omit a section.
+4. **Preview and export:** Select a voice, preview the result and export individual A4 PDFs to a local folder.
+5. **Project management:** Reopen, rename or delete individual projects; clear the entire local project list after confirmation.
+
+---
+
+## 🛠️ New in v0.2.1: Developer Identity & Repository Integration
+
+* **Developer credit:** APK by Manuel Pollhammer 2026, linked directly to [pollhammer.org](https://www.pollhammer.org).
+* **GitHub repository shortcut:** Open the official project repository from the app menu, below Reset Zoom.
+* **Offline architecture retained:** Both optional links open the external browser; the app itself still has no internet permission.
+* **Project documentation:** README structured in the style of [Office-Morph](https://github.com/pollhammer/office-morph), with an updated project banner, description and installation instructions.
+
+---
+
+## ✨ Key Features
+
+* **Smart Staff Detection:** Finds potential cut positions in the whitespace between staves.
+* **Manual Marker Editing:** Add, remove or drag separators to fine-tune the extraction.
+* **Zoom:** Enlarge the score up to 350% with horizontal scrolling.
+* **Reusable Presets:** Store and reuse typical instrumental or vocal lineups.
+* **Original Quality:** Vector-based PDF export preserves source vectors and embedded images where supported.
+* **Raster Mode:** Export only visible rendered score sections as an alternative.
+* **A4 Layout:** Automatically arrange selected score sections on output pages.
+* **Progress Feedback:** Percentage and page/part status during preview, assignment and export.
+* **Local Project Storage:** Save work on-device, with explicit confirmation before permanent deletion.
+* **No Ads, No Account:** Core functions operate entirely offline.
+
+---
+
+## 📋 Prerequisites & Installation
+
+* Android 5.0 (API 21) or higher.
+* A locally accessible PDF score and available storage.
+* Download the latest successful **NotenSplit-Offline-0.2.1-APK** artifact from [GitHub Actions](https://github.com/pollhammer/NotenSplit-Offline/actions), extract the ZIP and open the APK. Android may request permission to install from this source.
+* This is a debug-signed test build. v0.2.1 uses a separate application ID to protect existing v0.1 and v0.2 projects against accidental data loss; those projects remain in their original apps and are not migrated automatically.
+
+## ⚙️ Build from Source
+
+JDK 17, Android SDK 35 and Gradle 8.9 are required for a local build.
+
+```bash
+bash tests/test.sh
+gradle --no-daemon :app:assembleDebug
+```
+
+The automated workflow checks APK signatures and verifies the absence of `android.permission.INTERNET`.
+
+## ⚠️ Limitations
+
+Staff recognition is heuristic, not optical music recognition. Inspect and adjust markers before exporting. Original-quality PDF export uses clipping: hidden source content may remain embedded. Choose raster mode if only visible content should be retained. The app does not reproduce every Partifi feature, and device-level validation of each update is recommended.
+
+## 🔗 Links
+
+* **Developer:** [www.pollhammer.org](https://www.pollhammer.org)
+* **Repository:** [pollhammer/NotenSplit-Offline](https://github.com/pollhammer/NotenSplit-Offline)
+* **APK builds:** [GitHub Actions](https://github.com/pollhammer/NotenSplit-Offline/actions)
+* **Inspiration:** [Partifi](https://partifi.org/)
+* **PDF library:** [PDFBox-Android](https://github.com/TomRoush/PdfBox-Android) (Apache License 2.0)
+
+---
+
+**Developed by Manuel Pollhammer | Release 2026**
diff --git a/app/build.gradle b/app/build.gradle
new file mode 100644
index 0000000..cd6c229
--- /dev/null
+++ b/app/build.gradle
@@ -0,0 +1,10 @@
+plugins { id 'com.android.application' }
+android {
+ namespace 'at.notensplit.offline'
+ compileSdk 35
+ defaultConfig { applicationId 'at.notensplit.offline.v21'; minSdk 21; targetSdk 34; versionCode 3; versionName '0.2.1' }
+ 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
new file mode 100644
index 0000000..4634da8
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/app/src/main/java/at/notensplit/offline/MainActivity.java b/app/src/main/java/at/notensplit/offline/MainActivity.java
new file mode 100644
index 0000000..d5ca8d6
--- /dev/null
+++ b/app/src/main/java/at/notensplit/offline/MainActivity.java
@@ -0,0 +1,195 @@
+package at.notensplit.offline;
+
+import android.app.*;
+import android.content.*;
+import android.database.Cursor;
+import android.graphics.*;
+import android.graphics.pdf.*;
+import android.net.Uri;
+import android.os.*;
+import android.provider.*;
+import android.view.*;
+import android.widget.*;
+import org.json.*;
+import java.io.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+public class MainActivity extends Activity {
+ private static final int PICK_PDF=10, PICK_FOLDER=11;
+ private static final int INK=0xff203044;
+ private final ExecutorService worker=Executors.newSingleThreadExecutor();
+ private File root, project;
+ private String title="";
+ private int pageIndex=0, pageCount=0;
+ private final TreeMap pages=new TreeMap<>();
+ private Bitmap preview;
+ private LinearLayout editor;
+ private TextView status, pageLabel, hint;
+ private ScoreView score;
+ 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<>();
+ final ArrayList names=new ArrayList<>();
+ boolean initialized=false;
+ PageData(){names.add("");}
+ float top(int i){return i==0?0:cuts.get(i-1);}
+ float bottom(int i){return i==cuts.size()?1:cuts.get(i);}
+ int segment(float y){int i=0;while(i=cuts.get(i))i++;return i;}
+ void insert(float y){int i=segment(y);if(y-top(i)<.008f || bottom(i)-y<.008f)return;cuts.add(i,y);names.add(i+1,"");}
+ 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();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(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(8),dp(5),dp(8),dp(5));layout.setBackgroundColor(0xfff2f5f5);setContentView(layout);
+ TextView heading=text("NotenSplit Offline · 0.2.1",20);heading.setTypeface(null,Typeface.BOLD);layout.addView(heading);
+ TextView credit=text("APK by Manuel Pollhammer 2026",12);credit.setTextColor(0xff176c65);credit.setPaintFlags(credit.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);credit.setPadding(0,dp(2),0,dp(4));credit.setContentDescription("APK by Manuel Pollhammer 2026 – Homepage im Browser öffnen");credit.setOnClickListener(v->openExternal("https://www.pollhammer.org"));layout.addView(credit);
+ 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));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,"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();
+ 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");}
+ private void help(){new AlertDialog.Builder(this).setTitle("So funktioniert NotenSplit").setMessage("1. Partitur als PDF öffnen. Notensysteme werden näherungsweise erkannt.\n\n2. Trennlinien durch Ziehen verschieben, mit + ergänzen oder mit − entfernen. Abschnitt antippen und benennen. Unter Stimmenfolge lassen sich wiederkehrende Instrumente automatisch zuweisen.\n\n3. Titel oder gemeinsame Angaben als 'all' benennen, damit sie in alle Stimmen kopiert werden. 'skip' lässt einen Abschnitt weg. Nicht benannte Abschnitte werden ebenfalls ausgelassen.\n\n4. Vorschau oder PDF-Export wählen. Die fertigen PDFs werden in den gewählten Ordner geschrieben.\n\nÄnderungen werden lokal gespeichert. Die Erkennung ist eine Näherung; kontrolliere jede Seite. Kein Internet, keine Anmeldung.").setPositiveButton("OK",null).show();}
+ private void pickPdf(){Intent i=new Intent(Intent.ACTION_OPEN_DOCUMENT);i.setType("application/pdf");i.addCategory(Intent.CATEGORY_OPENABLE);startActivityForResult(i,PICK_PDF);}
+ private void pickFolder(){if(!checkLabels())return;int missing=pageCount-pages.size();int empty=0;for(PageData p:pages.values())for(String n:p.names)if(n.isEmpty())empty++;if(missing>0||empty>0){new AlertDialog.Builder(this).setTitle("Unvollständige Partitur").setMessage(missing+" noch nicht bearbeitete Seiten, "+empty+" unbenannte Abschnitte. Diese werden beim Export ausgelassen.").setNegativeButton("Abbrechen",null).setPositiveButton("Trotzdem exportieren",(d,w)->launchFolder()).show();return;}launchFolder();}
+ private void launchFolder(){Intent i=new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);startActivityForResult(i,PICK_FOLDER);}
+ @Override protected void onActivityResult(int request,int result,Intent data){super.onActivityResult(request,result,data);if(result!=RESULT_OK || data==null || data.getData()==null)return;Uri uri=data.getData();if(request==PICK_PDF)importPdf(uri);else if(request==PICK_FOLDER)export(uri);}
+ private void importPdf(Uri uri){String name="Partitur";try(Cursor c=getContentResolver().query(uri,new String[]{OpenableColumns.DISPLAY_NAME},null,null,null)){if(c!=null&&c.moveToFirst())name=c.getString(0);}catch(Exception ignored){}final String label=name;final File dir=new File(root,UUID.randomUUID().toString());dir.mkdirs();runTask("PDF wird importiert …",()->{try(InputStream in=getContentResolver().openInputStream(uri);OutputStream out=new FileOutputStream(new File(dir,"score.pdf"))){if(in==null)throw new IOException("Datei nicht verfügbar");byte[] b=new byte[65536];int n;while((n=in.read(b))!=-1)out.write(b,0,n);}try(PdfRenderer r=renderer(dir)){if(r.getPageCount()==0)throw new IOException("Leere PDF");}JSONObject j=new JSONObject();j.put("title",label);j.put("page",0);j.put("pages",new JSONObject());writeJson(dir,j);return dir;},v->{try{openProject(v);}catch(Exception e){error(e);}});}
+ 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);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{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;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","GitHub Repository"};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;case 6:openExternal("https://github.com/pollhammer/NotenSplit-Offline");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.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");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){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 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()){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;}
+ float drawnWidth=b.getWidth()*localScale;float x=(595-drawnWidth)/2;
+ output.getCanvas().drawBitmap(b,new Rect(0,top,b.getWidth(),bottom),new RectF(x,y,x+drawnWidth,y+height),paint);y+=height+9;
+ }}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.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 openExternal(String url){try{Intent i=new Intent(Intent.ACTION_VIEW,Uri.parse(url));i.addCategory(Intent.CATEGORY_BROWSABLE);startActivity(i);}catch(ActivityNotFoundException e){toast("Kein Browser verfügbar");}}
+ 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 base=horizontal!=null&&horizontal.getWidth()>0?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_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;
+ default:return true;
+ }}
+ @Override public boolean performClick(){super.performClick();return true;}
+ }
+}
diff --git a/app/src/main/java/at/notensplit/offline/StaffDetector.java b/app/src/main/java/at/notensplit/offline/StaffDetector.java
new file mode 100644
index 0000000..06e43ff
--- /dev/null
+++ b/app/src/main/java/at/notensplit/offline/StaffDetector.java
@@ -0,0 +1,31 @@
+package at.notensplit.offline;
+import java.util.ArrayList;
+import java.util.List;
+public final class StaffDetector {
+ private StaffDetector(){}
+ public static List detect(int[] pixels,int width,int height){
+ List lines=new ArrayList<>();
+ int left=width/12,right=width-left,minRun=Math.max(12,(right-left)*23/100),start=-1;
+ for(int y=0;y>16)&255)*3+((p>>8)&255)*6+(p&255);if(lum<1700){run++;dark++;best=Math.max(best,run);}else run=0;}
+ boolean line=best>=minRun||dark>(right-left)*.63;
+ if(line&&start<0)start=y;
+ if((!line||y==height-1)&&start>=0){int end=line?y:y-1;if(end-start<=Math.max(3,height/180))lines.add((start+end)/2);start=-1;}
+ }
+ 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>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
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..e5ce0d9
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1 @@
+plugins { id 'com.android.application' version '8.7.3' apply false }
diff --git a/logo/logo.svg b/logo/logo.svg
new file mode 100644
index 0000000..519f4f0
--- /dev/null
+++ b/logo/logo.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..401ef8b
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,4 @@
+pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
+dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
+rootProject.name = 'NotenSplitOffline'
+include ':app'
diff --git a/tests/StaffDetectorTest.java b/tests/StaffDetectorTest.java
new file mode 100644
index 0000000..92f1a06
--- /dev/null
+++ b/tests/StaffDetectorTest.java
@@ -0,0 +1,13 @@
+import at.notensplit.offline.StaffDetector;
+import java.util.*;
+public class StaffDetectorTest {
+ public static void main(String[] args) {
+ int w=800,h=1000; int[] p=new int[w*h]; Arrays.fill(p,0xffffffff);
+ for(int start:new int[]{100,240,600}) for(int k=0;k<5;k++) for(int x=65;x<735;x++) p[(start+k*8)*w+x]=0xff000000;
+ List cuts=StaffDetector.detect(p,w,h);
+ if(cuts.size()!=2 || Math.abs(cuts.get(0)-.186f)>.001 || Math.abs(cuts.get(1)-.436f)>.001) throw new AssertionError(cuts);
+ Arrays.fill(p,0xffffffff);
+ if(!StaffDetector.detect(p,w,h).isEmpty()) throw new AssertionError("blank page");
+ System.out.println("StaffDetector: 2 tests passed");
+ }
+}
diff --git a/tests/test.sh b/tests/test.sh
new file mode 100644
index 0000000..edf2544
--- /dev/null
+++ b/tests/test.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+set -e
+d=$(mktemp -d)
+trap 'rm -rf "$d"' EXIT
+javac -d "$d" app/src/main/java/at/notensplit/offline/StaffDetector.java tests/StaffDetectorTest.java
+java -cp "$d" StaffDetectorTest