Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 42.07 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package imp.trading;
  7.  
  8. import imp.ImproVisor;
  9. import imp.com.CommandManager;
  10. import imp.data.Chord;
  11. import imp.data.ChordPart;
  12. import imp.data.Key;
  13. import imp.data.MelodyPart;
  14. import imp.data.NoteSymbol;
  15. import imp.data.RhythmCluster;
  16. import imp.data.Score;
  17. import imp.data.Transposition;
  18. import imp.data.advice.Advice;
  19. import imp.data.advice.AdviceForMelody;
  20. import imp.data.advice.AdviceForRhythm;
  21. import imp.generalCluster.Cluster;
  22. import imp.generalCluster.CreateGrammar;
  23. import imp.generalCluster.DataPoint;
  24. import imp.gui.Notate;
  25. import static imp.gui.Notate.DEFAULT_BARS_PER_PART;
  26. import imp.trading.tradingResponseModes.CorrectRhythmTRM;
  27. import imp.trading.tradingResponseModes.RhythmHelperTRM;
  28. import imp.trading.tradingResponseModes.TradingResponseMode;
  29. import imp.util.NonExistentParameterException;
  30. import imp.util.Preferences;
  31. import java.awt.Component;
  32. import java.awt.Graphics;
  33. import java.awt.GridBagConstraints;
  34. import java.awt.GridBagLayout;
  35. import java.awt.Image;
  36. import java.awt.event.ActionEvent;
  37. import java.awt.event.ActionListener;
  38. import java.awt.event.MouseEvent;
  39. import java.awt.event.MouseListener;
  40. import java.awt.image.BufferedImage;
  41. import java.io.BufferedReader;
  42. import java.io.BufferedWriter;
  43. import java.io.File;
  44. import java.io.FileReader;
  45. import java.io.FileWriter;
  46. import java.io.IOException;
  47. import java.io.Reader;
  48. import java.io.Writer;
  49. import java.util.ArrayList;
  50. import java.util.logging.Level;
  51. import java.util.logging.Logger;
  52. import javax.imageio.ImageIO;
  53. import javax.swing.Box;
  54. import javax.swing.BoxLayout;
  55. import javax.swing.ImageIcon;
  56. import javax.swing.JButton;
  57. import javax.swing.JCheckBox;
  58. import javax.swing.JLabel;
  59. import javax.swing.JPanel;
  60. import javax.swing.JScrollPane;
  61. import javax.swing.JSplitPane;
  62. import javax.swing.JTextField;
  63. import javax.swing.text.Element;
  64. import javax.swing.text.html.ImageView;
  65. import polya.Polylist;
  66.  
  67. /**
  68. *
  69. * @author cssummer17
  70. */
  71. public class UserRhythmSelecterDialog extends javax.swing.JDialog implements java.beans.Customizer {
  72.  
  73. private Object bean;
  74. /*
  75. The list of rhythm clusters from the last trading session
  76. */
  77. private ArrayList<RhythmCluster> rhythmClusters;
  78. /*
  79. The list of datapoints for all of the rhythms played by the user in the last session
  80. */
  81. private ArrayList<DataPoint> userData;
  82. public static final java.awt.Point INITIAL_OPEN_POINT = new java.awt.Point(25, 0);
  83. /*
  84. An array of checkbox's from the add panel. Syncronized with userData to keep track of which rhythms to add and which rhythms are left to add
  85. */
  86. private ArrayList<JCheckBox> checkBoxArray;
  87.  
  88. private TradingResponseInfo tradingResponseInfo;
  89. private Notate notate;
  90.  
  91. private JButton addButton;
  92. private JButton deleteButton;
  93. private ArrayList<DataPoint> selectedRhythms;
  94. /*
  95. An array of checkbox's from the editor panel. Syncronized with userRuleStringsToWrite to keep track of which rhythms will be deleted or not
  96. */
  97. private ArrayList<JCheckBox> editorCheckBoxArray;
  98. //private ArrayList<Polylist> userRhythms;
  99. private static boolean addedRhythm = false;
  100. ArrayList<Polylist> userRhythms;
  101. ArrayList<Polylist> userRuleStrings;
  102. JScrollPane editorScrollPane;
  103. JScrollPane UserRhythmScrollPane;
  104. private JPanel rhythmTextPanel;
  105. private JPanel editorPanel;
  106. private ArrayList<Polylist> userRuleStringsToWrite;
  107. String filePath;
  108. private ArrayList<Polylist> rhythmsToDelete;
  109. private int windowSize;
  110. private Double[] maxMetricValues;
  111. private Double[] minMetricValues;
  112. private int totalNumDataPointsSaved;
  113. private ArrayList<DataPoint> dataPointsAdded;
  114. private RhythmHelperTRM rhythmHelperTRM;
  115. private JLabel gradeLabel;
  116.  
  117.  
  118.  
  119. /**
  120. * Creates new customizer UserRhythmSelecterDialog
  121. */
  122. public UserRhythmSelecterDialog(TradingResponseMode trm) {
  123. if( !(trm instanceof RhythmHelperTRM) ){
  124. System.out.println("As of now, UserRhythmSelecter Dialog only works with TRM's of type RhythmHelper! "
  125. + "Not going to show UserRhythmSelectorDialog.");
  126. dispose();
  127. }
  128.  
  129. rhythmHelperTRM = (RhythmHelperTRM) trm;
  130.  
  131. //this.tradingResponseInfo = tradingResponseInfo;
  132.  
  133. this.windowSize = rhythmHelperTRM.getWindowSizeOfCluster();
  134. this.rhythmClusters = rhythmHelperTRM.getRhythmClusters();
  135. this.notate = rhythmHelperTRM.getNotate();
  136.  
  137. this.selectedRhythms = new ArrayList<DataPoint>();
  138.  
  139. userData = getUsersData(rhythmClusters);
  140. dataPointsAdded = new ArrayList<DataPoint>();
  141.  
  142. filePath = retrieveUserRhythmsFileName();
  143. userRuleStringsToWrite = readInRuleStringsFromFile(filePath);
  144.  
  145. userRuleStrings = extractRuleStrings(userData);
  146. userRhythms = extractUserRhythms(userData);
  147.  
  148. rhythmsToDelete = new ArrayList<Polylist>();
  149.  
  150. maxMetricValues = rhythmHelperTRM.getMaxMetricVals();
  151. minMetricValues = rhythmHelperTRM.getMinMetricVals();
  152. totalNumDataPointsSaved = rhythmHelperTRM.getTotalNumSavedDataPoints();
  153.  
  154. System.out.println("in constructor, userRuleStringsToWrite: " + userRuleStringsToWrite.toString());
  155.  
  156. checkBoxArray = new ArrayList<JCheckBox>();
  157. editorCheckBoxArray = new ArrayList<JCheckBox>();
  158. initComponents();
  159.  
  160. createDialog(userRhythms);
  161.  
  162. addButton.addActionListener(new ActionListener(){
  163. public void actionPerformed(ActionEvent e){
  164. addSelectedRuleStrings();
  165. // try {
  166. // rewriteRhythmClustersToFile();
  167. // } catch (IOException ex) {
  168. // Logger.getLogger(UserRhythmSelecterDialog.class.getName()).log(Level.SEVERE, null, ex);
  169. // }
  170. refreshDialog();
  171. }
  172.  
  173. } );
  174.  
  175. deleteButton.addActionListener(new ActionListener(){
  176. public void actionPerformed(ActionEvent e){
  177. ArrayList<Polylist> deletedRhythms = removeRhythms();
  178. rhythmsToDelete.addAll(deletedRhythms);
  179. System.out.println("\n\nrefreshing editor pane...\n\n");
  180. refreshEditorPane();
  181.  
  182.  
  183. }
  184.  
  185.  
  186.  
  187. } );
  188.  
  189. this.addWindowListener(new java.awt.event.WindowAdapter() {
  190. @Override
  191. public void windowClosing(java.awt.event.WindowEvent windowEvent){
  192. saveChanges();
  193. }
  194. });
  195.  
  196. }
  197.  
  198. /*
  199. Get the file name from preferences and prepend the file path to it.
  200. */
  201. public String retrieveUserRhythmsFileName(){
  202. String fileName = getUserRhythmFileNameFromPreferences();
  203. fileName = ImproVisor.getRhythmClusterDirectory() + "/" + fileName;
  204. return fileName;
  205. }
  206.  
  207. /**
  208. * Get the file name for the user rhythms stored in the preferences file
  209. * @return
  210. */
  211. public String getUserRhythmFileNameFromPreferences(){
  212. String rtn = "";
  213. try{
  214. rtn = Preferences.getPreferenceQuietly(Preferences.MY_RHYTHMS_FILE);
  215. }catch(NonExistentParameterException e){
  216. System.out.println("No user rhythm file name found in preferences!");
  217. }
  218.  
  219.  
  220. return rtn;
  221. }
  222.  
  223. /**Takes Rule Strings represented as Polylist and writes them to the
  224. * file specified in filePath. Used to write the rhythms to the user rhythm file.
  225. *
  226. * @param filePath - path to the My.rhythms file
  227. */
  228. private void writeMyRuleStringPLsToFile(String filePath){
  229. Writer writer;
  230.  
  231. try {
  232. writer = new BufferedWriter(new FileWriter(filePath));
  233. for(int i = 0; i < userRuleStringsToWrite.size(); i++){
  234. Polylist ruleStringPL = userRuleStringsToWrite.get(i);
  235. writer.write(ruleStringPL.toString() + "\n");
  236. }
  237.  
  238.  
  239.  
  240. writer.close();
  241. } catch (IOException ex) {
  242. System.out.println("Could not write to file: " + filePath);
  243. Logger.getLogger(UserRhythmSelecterDialog.class.getName()).log(Level.SEVERE, null, ex);
  244. }
  245.  
  246. }
  247.  
  248. /**Takes RuleStrings from the file specified and return them in an ArrayList
  249. * represented as Polylists
  250. *
  251. * @param fileName
  252. * @return ArrayList of
  253. */
  254. public static ArrayList<Polylist> readInRuleStringsFromFile(String fileName){
  255. BufferedReader reader;
  256.  
  257. try {
  258. reader = new BufferedReader(new FileReader(fileName));
  259. ArrayList<Polylist> ruleStringPL=fillUserRuleStringsToWrite(reader);
  260. reader.close();
  261. return ruleStringPL;
  262.  
  263. } catch (IOException ex) {
  264. //Logger.getLogger(UserRhythmSelecterDialog.class.getName()).log(Level.SEVERE, null, ex);
  265. System.out.println("***Could not load user rhythms from file: " + fileName);
  266. System.out.println(ex);
  267. return new ArrayList<Polylist>();
  268. }
  269. }
  270.  
  271. /**Does the bulk of the work for readInRuleStringsFromFile, makes an ArrayList
  272. * of polylists of the ruleStrings in the BufferedReader passed in
  273. *
  274. * @param reader - buffered reader for file with rulestrings in it
  275. * @return ArrayList of ruleStrings represented as Polylists
  276. * @throws IOException - if theres a problem with the bufferedReader
  277. */
  278. public static ArrayList<Polylist> fillUserRuleStringsToWrite(BufferedReader reader) throws IOException{
  279. ArrayList<Polylist> ruleStringsFromFile = new ArrayList<Polylist>();
  280. String line = reader.readLine();
  281. while( line != null){
  282. Polylist ruleStringPL = (Polylist) Polylist.PolylistFromString(line).first();
  283. ruleStringsFromFile.add(ruleStringPL);
  284. line = reader.readLine();
  285. }
  286. return ruleStringsFromFile;
  287. }
  288.  
  289. public void showGrade(int numTrades){
  290. String introString = "Your Grade: ";
  291. String grade;
  292.  
  293. if (rhythmHelperTRM instanceof CorrectRhythmTRM){
  294. CorrectRhythmTRM correctRhythmTRM = (CorrectRhythmTRM) rhythmHelperTRM;
  295. double score = correctRhythmTRM.getScore();
  296. System.out.println("score to grade from: "+score);
  297. System.out.println("numTrades: "+ numTrades);
  298. if (score > CorrectRhythmTRM.A * numTrades){
  299. grade = "A";
  300. }else if(score > CorrectRhythmTRM.B *numTrades){
  301. grade = "B";
  302. }else if(score > CorrectRhythmTRM.C *numTrades){
  303. grade = "C";
  304. }else if(score > CorrectRhythmTRM.D *numTrades){
  305. grade = "D";
  306. }else{
  307. grade = "F";
  308. }
  309. gradeLabel.setText(introString+grade);
  310.  
  311. }else{
  312. gradeLabel.setText("sorry, no grade available");
  313. }
  314. gradeLabel.setVisible(true);
  315. }
  316.  
  317.  
  318.  
  319. /**Removes the rhythms in the array from the rhythm clusters they were placed into,
  320. * and writes the edited rhythmCluster to the file.
  321. *
  322. * @param rhythmsToExclude - rhythms to be deleted from their respective rhythmClusters
  323. * @throws IOException - if there's a problem writing to the rhythm Clusters file
  324. */
  325. private void deleteSelectedRhythmsFromClusters(ArrayList<Polylist> rhythmsToExclude) throws IOException {
  326. Cluster[] clusterArray = ClusterArrayListToClusterArray(rhythmClusters);
  327. CreateGrammar.selectiveClusterToFile(clusterArray, rhythmHelperTRM.getClusterFileName(), rhythmsToExclude, windowSize,
  328. maxMetricValues, minMetricValues);
  329.  
  330. }
  331.  
  332. /**Plays and displays the rhythm specified in the argument on the leadsheet, using middle
  333. * c for the pitch value
  334. *
  335. * @param userRhythm - rhythm to display
  336. */
  337. private void displayRhythmOnLeadsheet(String userRhythm){
  338. String[] userRhythmNoteStrings = userRhythm.split(" ");
  339. Polylist noteSymbolPolylist = new Polylist();
  340. Polylist pitchNoteSymbolPolylist = new Polylist();
  341. for (int i = 0; i < userRhythmNoteStrings.length; i++){
  342. NoteSymbol noteSymbol = NoteSymbol.makeNoteSymbol(userRhythmNoteStrings[i]);
  343. noteSymbolPolylist = noteSymbolPolylist.addToEnd(noteSymbol);
  344. pitchNoteSymbolPolylist = pitchNoteSymbolPolylist.addToEnd(NoteSymbol.makeNoteSymbol("c4"));
  345. }
  346.  
  347. Polylist notePolylistToWrite = NoteSymbol.newPitchesForNotes(noteSymbolPolylist, pitchNoteSymbolPolylist);
  348. System.out.println(notePolylistToWrite);
  349.  
  350. MelodyPart melodyPartToWrite = new MelodyPart(notePolylistToWrite.toStringSansParens());
  351. //System.out.println("melody part from user is: "+ melodyPartToWrite.toString());
  352.  
  353.  
  354. AdviceForMelody advice = new AdviceForMelody("RhythmPreview", notePolylistToWrite, "c", Key.getKey("c"),
  355. rhythmHelperTRM.getMetre(), 0);//make a new advice for melody object
  356.  
  357. advice.setNewPart(melodyPartToWrite);//new part of advice object is the part that gets pasted to the leadsheet
  358.  
  359. //
  360. //
  361. // Score newScore = new Score("");
  362. //
  363. //
  364. // int chordFontSize = Integer.valueOf(Preferences.getPreference(Preferences.DEFAULT_CHORD_FONT_SIZE));
  365. //
  366. // newScore.setChordFontSize(chordFontSize);
  367. //
  368. // newScore.setTempo(1);
  369. //
  370. // ChordPart chords = new ChordPart();
  371. //
  372. // chords.addChord(new Chord("NC")); // Some chord is ecessary to preven screw-ups
  373. //
  374. // newScore.setChordProg(chords);
  375. //
  376. //
  377. // /**@TODO don't hardcode measure length to 480*/
  378. // newScore.addPart(new MelodyPart(DEFAULT_BARS_PER_PART * 480));
  379. //
  380. // newScore.setStyle(Preferences.getPreference(Preferences.DEFAULT_STYLE));
  381. //
  382. // Transposition transposition =
  383. // new Transposition(notate.getIntFromSpinner(notate.getLeadsheetChordTranspositionSpinner()),
  384. // notate.getIntFromSpinner(notate.getLeadsheetBassTranspositionSpinner()),
  385. // notate.getIntFromSpinner(notate.getChorusMelodyTranspositionSpinner()));
  386. // newScore.setTransposition(transposition);
  387. //
  388. // // open a new window
  389. //
  390. // Notate invisibleNotate =
  391. // new Notate(newScore, Integer.MAX_VALUE, Integer.MAX_VALUE);
  392. //
  393. // /**@TODO decide if this makes it invisible*/
  394. // //newNotate.makeVisible(this);
  395. //
  396. // invisibleNotate.setTransposition(transposition);
  397. //
  398. //
  399. // invisibleNotate.makeVisible();
  400. //
  401. //
  402. //
  403. //
  404. // advice.insertInPart(invisibleNotate.getScore().getPart(0), 0, new CommandManager(), invisibleNotate);//insert melodyPartToWrite into the notate score
  405. // invisibleNotate.repaint();//refresh the notate page
  406. // BufferedImage bi = new BufferedImage(invisibleNotate.getSize().width, invisibleNotate.getSize().height-100, BufferedImage.TYPE_INT_ARGB);
  407. // Graphics g = bi.createGraphics();
  408. // invisibleNotate.paint(g);
  409. // g.dispose();
  410. // BufferedImage dest = bi.getSubimage(70, 290 ,980, 75);
  411. // System.out.println("about to save image!!!!!!!!");
  412. // invisibleNotate.dispose();
  413. // try{ImageIO.write(dest,"png", new File("screenGrab.png"));}
  414. // catch(Exception e){System.out.println("screen grab didn't work sorry :(");}
  415.  
  416. advice.insertInPart(notate.getScore().getPart(0), 0, new CommandManager(), notate);//insert melodyPartToWrite into the notate score
  417. notate.repaint();//refresh the notate page
  418. notate.playCurrentSelection(false, 0, false, "Printing Rhythm");//play the leadsheet
  419.  
  420. }
  421.  
  422.  
  423. /**
  424. * Updates the entire dialog. Updates both add rhythms panel (userRhythmScrollPane) and edit rhythms panel.
  425. * Refills these panels with new data after an add or a delete.
  426. */
  427. private void refreshDialog(){
  428. JPanel updatedUserContents = getRhythmPanel();
  429. UserRhythmScrollPane.setViewportView(updatedUserContents);
  430. UserRhythmScrollPane.revalidate();
  431.  
  432. JPanel updatedEditorContents = getEditorPanel();
  433. editorScrollPane.setViewportView(updatedEditorContents);
  434. editorScrollPane.revalidate();
  435.  
  436. this.repaint();
  437. }
  438.  
  439. /**
  440. * Just updates the edit rhythms panel.
  441. * Refills this panel with updated data after a rhythm has been removed.
  442. */
  443. private void refreshEditorPane(){
  444. //UserRhythmScrollPane.removeAll();
  445.  
  446. JPanel updatedEditorContents = getEditorPanel();
  447. editorScrollPane.setViewportView(updatedEditorContents);
  448. editorScrollPane.revalidate();
  449.  
  450. this.repaint();
  451. }
  452.  
  453.  
  454. /**
  455. * Removes rhythms from userRuleStringsToWrite and
  456. * updates the list of rhythms to delete from the rhythm clusters (deletedRhythms).
  457. *
  458. *
  459. * @return updated list of rhythms to delete from the rhythm clusters deletedRhythms
  460. */
  461. public ArrayList<Polylist> removeRhythms(){
  462. ArrayList<Polylist> remainingRuleStringPLs = new ArrayList<Polylist>();
  463. ArrayList<Polylist> deletedRhythms = new ArrayList<Polylist>();
  464.  
  465. for(int i = 0; i < editorCheckBoxArray.size(); i++){
  466. Polylist ruleStringPL = userRuleStringsToWrite.get(i);
  467. if(editorCheckBoxArray.get(i).isSelected()){
  468. deletedRhythms.add(getRhythmPolylistFromRuleStringPL(ruleStringPL));
  469. }else{
  470. remainingRuleStringPLs.add(ruleStringPL);
  471. }
  472. }
  473.  
  474. userRuleStringsToWrite = remainingRuleStringPLs;
  475. return deletedRhythms;
  476. }
  477.  
  478.  
  479.  
  480. /**
  481. * Adds all rhythms selected by a user in add panel to a rhythmCluster and
  482. * the list of user rules strings to be stored in the user rhythms file
  483. * (userRuleStringsToWrite).
  484. *
  485. * Finds the best fit cluster for each selected user rhythm and adds to that
  486. * cluster.
  487. */
  488. private void addSelectedRuleStrings(){
  489. ArrayList<DataPoint> updatedUserData = new ArrayList<DataPoint>();
  490. ArrayList<Polylist> updatedUserRhythms = new ArrayList<Polylist>();
  491.  
  492. for(int i = 0; i < checkBoxArray.size(); i++){
  493. if(checkBoxArray.get(i).isSelected()){
  494. DataPoint selectedDP = userData.get(i);
  495.  
  496. dataPointsAdded.add(selectedDP);
  497.  
  498. RhythmCluster rc = rhythmHelperTRM.findNearestCluster(rhythmClusters, selectedDP);
  499. Polylist ruleStringPL = extractRuleStringPolylistFromDatapoint(selectedDP);
  500.  
  501.  
  502. rc.addSelectedRuleString(ruleStringPL);//add datapoint to rhythm cluster
  503. userRuleStringsToWrite.add(ruleStringPL);
  504.  
  505. }else{//everything that is not selected should be displayed after selected rhythms have been added
  506.  
  507. updatedUserData.add(userData.get(i));
  508. updatedUserRhythms.add(userRhythms.get(i));
  509. }
  510. }
  511.  
  512. userData = updatedUserData;
  513. userRhythms = updatedUserRhythms;
  514. }
  515.  
  516.  
  517.  
  518.  
  519. /**
  520. * Used to convert an arrayList of clusters to an array of clusters.
  521. *
  522. * Necessary because clusterToFile takes an array of clusters.
  523. *
  524. * @param rcArrayList The arrayList of clusters.
  525. *
  526. * @return the array version of the arrayList.
  527. */
  528. private Cluster[] ClusterArrayListToClusterArray(ArrayList<RhythmCluster> rcArrayList){
  529. Cluster[] clusterArray = new Cluster[rcArrayList.size()];
  530. for(int i = 0; i < rcArrayList.size(); i++){
  531. clusterArray[i] = rcArrayList.get(i);
  532. }
  533. return clusterArray;
  534. }
  535.  
  536. /**
  537. * Rewrites the rhythm clusters with user rhythms added by user and without
  538. * user rhythms removed by user.
  539. *
  540. * @throws IOException if fileName argument to clusterToFile incorrect
  541. */
  542. private void rewriteRhythmClustersToFile() throws IOException{
  543. Cluster[] clusterArray = ClusterArrayListToClusterArray(rhythmClusters);
  544. CreateGrammar.clusterToFile(clusterArray, tradingResponseInfo.getClusterFileName(),windowSize);
  545. }
  546.  
  547.  
  548. /**
  549. * creates the scrollpane from which the user can delete their own rhythms.
  550. * This scrollpane will be filled with the editorPanel which contains
  551. * all available user rhythms.
  552. *
  553. * @return the scrollpane object with the editorPanel as the content
  554. */
  555. private JScrollPane createEditorScrollPane(){
  556. //Stick rhythmTextPanel into scroll pane and return completed scroll pane
  557. return (new JScrollPane(getEditorPanel(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
  558. }
  559.  
  560. /**
  561. * Creates the editorPanel which contains all of the user rhythms a user ever added to
  562. * the current user rhythms file. The user rhythms are extracted from the ruleStrings.
  563. *
  564. * converted from ruleString to this format:
  565. * [noteType][duration]+[noteType][duration]+....
  566. *
  567. * Becomes content of editor scrollpane.
  568. *
  569. * @return a JPanel object with all of the rhythms a user has ever added to
  570. * the current user rhythms file
  571. */
  572. private JPanel getEditorPanel(){
  573. editorPanel = new JPanel();
  574. editorPanel.setLayout(new GridBagLayout());
  575. editorCheckBoxArray = new ArrayList<JCheckBox>();
  576. //Set up constraints for rhythmTextPanel layout
  577. GridBagConstraints scrollConstraints = new GridBagConstraints();
  578. scrollConstraints.anchor = GridBagConstraints.NORTH;
  579. scrollConstraints.weighty = 1;
  580. scrollConstraints.gridx = 0;
  581. scrollConstraints.fill = GridBagConstraints.HORIZONTAL;
  582. scrollConstraints.gridy = 0;
  583.  
  584. //Fill rhythmTextPanel with rhythms
  585.  
  586.  
  587. for (int i = 0; i < userRuleStringsToWrite.size();i++){
  588. Polylist rhythm = userRuleStringsToWrite.get(i);
  589.  
  590. //System.out.println("rhythm is: " + rhythm);
  591.  
  592. String visualization = getVisualizationFromRuleStringPolylist(rhythm);
  593.  
  594. JTextField rhythmTextRepresentation = new JTextField();
  595. rhythmTextRepresentation.setText(visualization);
  596. rhythmTextRepresentation.setEditable(false);
  597. addMouseListenerToRhythmTextField(rhythmTextRepresentation);
  598.  
  599. //System.out.println("current visualization: "+ visualization);
  600.  
  601.  
  602. scrollConstraints.gridx = 0;
  603. JCheckBox temp = new JCheckBox();
  604. editorPanel.add(temp, scrollConstraints);
  605. editorCheckBoxArray.add(temp);
  606. scrollConstraints.gridx = 1;
  607. editorPanel.add(rhythmTextRepresentation, scrollConstraints);
  608. scrollConstraints.gridy++;
  609. }
  610. return editorPanel;
  611. }
  612.  
  613. /**
  614. * Writes the rule strings (aka rhythms) that a user wants to keep to the
  615. * user rhythms file specified in My.prefs. Also rewrites the cluster files
  616. * so that the rhythms a user wishes to delete are not written.
  617. */
  618. private void saveChanges(){
  619. writeMyRuleStringPLsToFile(filePath);
  620. try {
  621. deleteSelectedRhythmsFromClusters(rhythmsToDelete);
  622. } catch (IOException ex) {
  623. Logger.getLogger(UserRhythmSelecterDialog.class.getName()).log(Level.SEVERE, null, ex);
  624. }
  625. }
  626.  
  627. /**
  628. * Creates the entire userRhythmSelecterDialog.
  629. *
  630. * Two scrollpanes (add and edit) are in a splitpane which is itself in a
  631. * panel. Underneath the splitpane is the save/close button.
  632. *
  633. * @param userRhythms (not really used anymore)
  634. */
  635. private void createDialog(ArrayList<Polylist> userRhythms){
  636. //Create the panel that constains everything in dialog
  637. JPanel framePanel = new JPanel();
  638. framePanel.setLayout(new BoxLayout(framePanel, BoxLayout.Y_AXIS));
  639.  
  640. //add label for the add side
  641. JLabel addLabel = new JLabel("Add Selected Rhythms to Preferences");
  642. framePanel.add(addLabel);
  643.  
  644. //Create and add scroll pane with user rhythms to dialog
  645. UserRhythmScrollPane = createUserRhythmsScrollPane(userRhythms);
  646. framePanel.add(UserRhythmScrollPane);
  647.  
  648. //Create and add add button to dialog
  649. addButton = getAddButton();
  650. addButton.setAlignmentX(Component.CENTER_ALIGNMENT);
  651. framePanel.add(addButton);
  652.  
  653. //Create The User Rhythm Editor panel
  654. JPanel editorPanel = new JPanel();
  655. editorPanel.setLayout(new BoxLayout(editorPanel, BoxLayout.Y_AXIS));
  656.  
  657. //create the editor label
  658. JLabel editorLabel = new JLabel("Remove Selected Rhythms from Preferences");
  659. editorPanel.add(editorLabel);
  660.  
  661. //Create the editor scrollView
  662. editorScrollPane = createEditorScrollPane();
  663. editorScrollPane.setAlignmentX(Component.CENTER_ALIGNMENT);
  664. editorPanel.add(editorScrollPane);
  665.  
  666. //create the delete rhythm button
  667. deleteButton = getDeleteButton();
  668. deleteButton.setAlignmentX(Component.LEFT_ALIGNMENT);
  669. editorPanel.add(deleteButton);
  670.  
  671. //make split pane with editor and frame components
  672. JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,framePanel, editorPanel);
  673. splitPane.setDividerLocation(this.getWidth() / 2);
  674. //add the framePanel to the window
  675.  
  676. JPanel outerPanel = new JPanel();
  677. outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
  678. splitPane.setAlignmentX(Component.CENTER_ALIGNMENT);
  679. outerPanel.add(splitPane);
  680.  
  681. JButton closeButton = new JButton("Save");
  682. closeButton.setAlignmentX(Component.RIGHT_ALIGNMENT);
  683. closeButton.addActionListener(new ActionListener(){
  684. public void actionPerformed(ActionEvent e){
  685. saveChanges();
  686. dispose();
  687. }
  688. } );
  689.  
  690.  
  691. gradeLabel = new JLabel();
  692. gradeLabel.setVisible(false);
  693. outerPanel.add(gradeLabel);
  694.  
  695. outerPanel.add(closeButton);
  696.  
  697. this.add(outerPanel);
  698.  
  699. }
  700.  
  701. /**
  702. * Creates the add button which is to be put in the add scrollpane.
  703. *
  704. * @return the add button
  705. */
  706. private JButton getAddButton(){
  707. JButton button = new JButton("Add Rhythms");
  708. button.setAlignmentX(Component.CENTER_ALIGNMENT);
  709. return button;
  710. }
  711.  
  712. /**
  713. * Creates the delete button which is to be put in the edit scrollpane.
  714. *
  715. * @return the delete button
  716. */
  717. private JButton getDeleteButton(){
  718. JButton button = new JButton("Delete Selected Rhythms");
  719. button.setAlignmentX(Component.CENTER_ALIGNMENT);
  720. return button;
  721. }
  722.  
  723.  
  724.  
  725. /**
  726. * creates the scrollpane from which the user can add their own rhythms.
  727. * This scrollpane will be filled with the rhythm which contains
  728. * all rhythms played by user in last trading session.
  729. *
  730. * @return the scrollpane object with the rhythmPanel as the content
  731. */
  732. private JScrollPane createUserRhythmsScrollPane(ArrayList<Polylist> userRhythms){
  733.  
  734. //Stick rhythmTextPanel into scroll pane and return completed scroll pane
  735. return (new JScrollPane(getRhythmPanel(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
  736.  
  737. }
  738.  
  739. /**
  740. * Creates the rhythmPanel which contains all of the rhythms a user played
  741. * in the last trading session. The user rhythms are extracted from ruleStrings.
  742. *
  743. * added in this format:
  744. * [noteType][duration]+[noteType][duration]+....
  745. *
  746. * Becomes content of add scrollpane.
  747. *
  748. * @return a JPanel object with all of the rhythms a user played in the last
  749. * trading session.
  750. */
  751. private JPanel getRhythmPanel(){
  752. JPanel rhythmTextPanel = new JPanel();
  753. rhythmTextPanel.setLayout(new GridBagLayout());
  754. checkBoxArray = new ArrayList<JCheckBox>();
  755. //Set up constraints for rhythmTextPanel layout
  756. GridBagConstraints scrollConstraints = new GridBagConstraints();
  757. scrollConstraints.anchor = GridBagConstraints.NORTH;
  758. scrollConstraints.weighty = 1;
  759. scrollConstraints.gridx = 0;
  760. scrollConstraints.fill = GridBagConstraints.HORIZONTAL;
  761. scrollConstraints.gridy = 0;
  762.  
  763.  
  764. //Fill rhythmTextPanel with rhythms
  765. for(int i = 0; i < userRhythms.size(); i++){
  766. //JTextField rhythmTextRepresentation = new JTextField();
  767. //rhythmTextRepresentation.setText(makeRealMelodyFromRhythmPolylist(userRhythms.get(i)));
  768. //rhythmTextRepresentation.setEditable(false);
  769. //addMouseListenerToRhythmTextField(rhythmTextRepresentation);
  770. BufferedImage rhythmPic = createRhythmImage(makeRealMelodyFromRhythmPolylist(userRhythms.get(i)), i);
  771. Image resizedRhythmPic = rhythmPic.getScaledInstance((int) (rhythmPic.getWidth() / 2.5), (int) (rhythmPic.getHeight() / 2.5), Image.SCALE_SMOOTH);
  772. //System.out.println("rhythmPic.getWidth(): " + rhythmPic.getWidth());
  773. //System.out.println("rhythmPic.getHeight();: " + rhythmPic.getHeight());
  774. //ImageIcon rhythmIcon = new ImageIcon(rhythmPic);
  775.  
  776. ImageIcon rhythmIcon = new ImageIcon(resizedRhythmPic);
  777.  
  778. JLabel rhythmLabel = new JLabel(rhythmIcon);
  779. //System.out.println("current visualization: "+ makeRealMelodyFromRhythmPolylist(userRhythms.get(i)));
  780. scrollConstraints.gridx = 0;
  781. JCheckBox temp = new JCheckBox();
  782. rhythmTextPanel.add(temp, scrollConstraints);
  783. checkBoxArray.add(temp);
  784. scrollConstraints.gridx = 1;
  785. rhythmTextPanel.add(rhythmLabel, scrollConstraints);
  786. scrollConstraints.gridy++;
  787. }
  788.  
  789. return rhythmTextPanel;
  790. }
  791.  
  792. public BufferedImage createRhythmImage(String userRhythm, int idNum){
  793. String[] userRhythmNoteStrings = userRhythm.split(" ");
  794. Polylist noteSymbolPolylist = new Polylist();
  795. Polylist pitchNoteSymbolPolylist = new Polylist();
  796. for (int i = 0; i < userRhythmNoteStrings.length; i++){
  797. NoteSymbol noteSymbol = NoteSymbol.makeNoteSymbol(userRhythmNoteStrings[i]);
  798. noteSymbolPolylist = noteSymbolPolylist.addToEnd(noteSymbol);
  799. pitchNoteSymbolPolylist = pitchNoteSymbolPolylist.addToEnd(NoteSymbol.makeNoteSymbol("c4"));
  800. }
  801.  
  802. Polylist notePolylistToWrite = NoteSymbol.newPitchesForNotes(noteSymbolPolylist, pitchNoteSymbolPolylist);
  803. System.out.println(notePolylistToWrite);
  804.  
  805. MelodyPart melodyPartToWrite = new MelodyPart(notePolylistToWrite.toStringSansParens());
  806. //System.out.println("melody part from user is: "+ melodyPartToWrite.toString());
  807.  
  808.  
  809. AdviceForMelody advice = new AdviceForMelody("RhythmPreview", notePolylistToWrite, "c", Key.getKey("c"),
  810. rhythmHelperTRM.getMetre(), 0);//make a new advice for melody object
  811.  
  812. advice.setNewPart(melodyPartToWrite);//new part of advice object is the part that gets pasted to the leadsheet
  813.  
  814.  
  815.  
  816. Score newScore = new Score("");
  817.  
  818.  
  819. int chordFontSize = Integer.valueOf(Preferences.getPreference(Preferences.DEFAULT_CHORD_FONT_SIZE));
  820.  
  821. newScore.setChordFontSize(chordFontSize);
  822.  
  823. newScore.setTempo(1);
  824.  
  825. ChordPart chords = new ChordPart();
  826.  
  827. chords.addChord(new Chord("NC")); // Some chord is ecessary to preven screw-ups
  828.  
  829. newScore.setChordProg(chords);
  830.  
  831.  
  832. /**@TODO don't hardcode measure length to 480*/
  833. newScore.addPart(new MelodyPart(DEFAULT_BARS_PER_PART * 480));
  834.  
  835. newScore.setStyle(Preferences.getPreference(Preferences.DEFAULT_STYLE));
  836.  
  837. Transposition transposition =
  838. new Transposition(notate.getIntFromSpinner(notate.getLeadsheetChordTranspositionSpinner()),
  839. notate.getIntFromSpinner(notate.getLeadsheetBassTranspositionSpinner()),
  840. notate.getIntFromSpinner(notate.getChorusMelodyTranspositionSpinner()));
  841. newScore.setTransposition(transposition);
  842.  
  843. // open a new window
  844.  
  845. Notate invisibleNotate =
  846. new Notate(newScore, Integer.MAX_VALUE, Integer.MAX_VALUE);
  847. //
  848. //
  849. // Notate invisibleNotate =
  850. // new Notate(newScore);
  851.  
  852. /**@TODO decide if this makes it invisible*/
  853. //newNotate.makeVisible(this);
  854.  
  855. invisibleNotate.setTransposition(transposition);
  856.  
  857.  
  858. invisibleNotate.makeVisible();
  859.  
  860.  
  861.  
  862.  
  863. advice.insertInPart(invisibleNotate.getScore().getPart(0), 0, new CommandManager(), invisibleNotate);//insert melodyPartToWrite into the notate score
  864. invisibleNotate.getCurrentStave().setSelection(invisibleNotate.getCurrentStave().getMelodyPart().size() - 1);
  865. invisibleNotate.repaint();//refresh the notate page
  866.  
  867.  
  868. BufferedImage notateScreenshot = new BufferedImage(invisibleNotate.getSize().width, invisibleNotate.getSize().height-100, BufferedImage.TYPE_INT_ARGB);
  869. Graphics g = notateScreenshot.createGraphics();
  870.  
  871. invisibleNotate.paint(g);
  872. invisibleNotate.paint(g);
  873. g.dispose();
  874.  
  875.  
  876. g.dispose();
  877. System.out.println("width: " + notateScreenshot.getWidth());
  878. System.out.println("height: " + notateScreenshot.getHeight());
  879. int notateScreenshotWidth = notateScreenshot.getWidth();
  880. int notateScreenshotHeight = notateScreenshot.getHeight();
  881. int croppedXStart = (int) (0.069 * notateScreenshotWidth);//(75 / notateScreenshotWidth);
  882. int croppedYStart = (int) (0.34 * notateScreenshotHeight);// * (290 / notateScreenshotWidth);
  883. int croppedWidth = (int) (0.855 * notateScreenshotWidth);
  884. int croppedHeight = (int) (0.08 * notateScreenshotHeight);
  885. //BufferedImage dest = bi;
  886. ///BufferedImage dest = notateScreenshot.getSubimage(78, 300, 963, 70);
  887. BufferedImage dest = notateScreenshot.getSubimage(croppedXStart, croppedYStart, croppedWidth, croppedHeight);
  888. System.out.println("about to save image!!!!!!!!");
  889. //invisibleNotate.dispose();
  890. String name = "rhythmImage"+idNum + ".png";
  891. try{ImageIO.write(dest,"png", new File(name));}
  892. catch(Exception e){System.out.println("screen grab didn't work sorry :(");}
  893.  
  894. // advice.insertInPart(notate.getScore().getPart(0), 0, new CommandManager(), notate);//insert melodyPartToWrite into the notate score
  895. // notate.repaint();//refresh the notate page
  896. // notate.playCurrentSelection(false, 0, false, "Printing Rhythm");//play the leadsheet
  897.  
  898. return dest;
  899. }
  900.  
  901. /**
  902. * Add mouse listener to a text field in the add rhythms panel.
  903. *
  904. * This
  905. * @param rhythmTextRepresentation
  906. */
  907. private void addMouseListenerToRhythmTextField(JTextField rhythmTextRepresentation){
  908. rhythmTextRepresentation.addMouseListener(new MouseListener(){
  909. public void mouseClicked(MouseEvent e){
  910. displayRhythmOnLeadsheet(rhythmTextRepresentation.getText());
  911. }
  912.  
  913. @Override
  914. public void mousePressed(MouseEvent e) {
  915. //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  916. }
  917.  
  918. @Override
  919. public void mouseReleased(MouseEvent e) {
  920. //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  921. }
  922.  
  923. @Override
  924. public void mouseEntered(MouseEvent e) {
  925. //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  926. }
  927.  
  928. @Override
  929. public void mouseExited(MouseEvent e) {
  930. //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  931. }
  932. }
  933. );
  934. }
  935.  
  936. private String makeRealMelodyFromRhythmPolylist(Polylist rhythmPolylist){
  937. String rtn = "";
  938. //get rid of tag
  939. if(!rhythmPolylist.isEmpty()){
  940. rhythmPolylist = rhythmPolylist.rest();
  941. }
  942.  
  943. while (!rhythmPolylist.isEmpty()){
  944. Polylist currentNote = (Polylist) rhythmPolylist.first();
  945. if (currentNote.first().equals("X")){
  946. rtn += "c";
  947. }else{
  948. rtn += "r";
  949. }
  950. rtn += currentNote.second() + " ";
  951. rhythmPolylist = rhythmPolylist.rest();
  952. }
  953. return rtn;
  954. }
  955.  
  956. private ArrayList<DataPoint> getUsersData(ArrayList<RhythmCluster> rhythmClusters){
  957. ArrayList<DataPoint> userData = new ArrayList<DataPoint>();
  958. for(int i = 0; i < rhythmClusters.size(); i++){
  959. ArrayList<DataPoint> rcData = rhythmClusters.get(i).getUserDataPoints();
  960. for(int j = 0; j < rcData.size(); j++){
  961. userData.add(rcData.get(j));
  962. }
  963. }
  964. return userData;
  965. }
  966.  
  967. public void setObject(Object bean) {
  968. this.bean = bean;
  969. }
  970.  
  971. /**
  972. * This method is called from within the constructor to initialize the form.
  973. * WARNING: Do NOT modify this code. The content of this method is always
  974. * regenerated by the FormEditor.
  975. */
  976. // <editor-fold defaultstate="collapsed" desc="Generated Code">
  977. private void initComponents()
  978. {
  979. }// </editor-fold>
  980.  
  981. private ArrayList<Polylist> extractUserRhythms(ArrayList<DataPoint> userData) {
  982. ArrayList<Polylist> userRhythms = new ArrayList<Polylist>();
  983. for(int i = 0; i < userData.size(); i++){
  984. userRhythms.add(userData.get(i).getRelativePitchPolylist());
  985. }
  986.  
  987. return userRhythms;
  988. }
  989.  
  990. private Polylist extractRuleStringPolylistFromDatapoint(DataPoint d){
  991. String ruleStringString = "(userRuleString " + d.getRuleString() + ")";
  992. Polylist ruleStringPL = Polylist.PolylistFromString(ruleStringString);
  993. return (Polylist) ruleStringPL.first();
  994. }
  995.  
  996. private ArrayList<Polylist> extractRuleStrings(ArrayList<DataPoint> userData) {
  997. ArrayList<Polylist> ruleStringsPL = new ArrayList<Polylist>();
  998.  
  999. for(int i = 0; i < userData.size(); i++){
  1000. String plString = "(userRuleString " + userData.get(i).getRuleString() + ")";
  1001. Polylist addPL = Polylist.PolylistFromString(plString);
  1002. addPL = (Polylist) addPL.first();
  1003.  
  1004. ruleStringsPL.add(addPL);
  1005.  
  1006. //test stuff
  1007. Polylist p = ruleStringsPL.get(i);
  1008.  
  1009. }
  1010.  
  1011. return ruleStringsPL;
  1012. }
  1013.  
  1014. private String getVisualizationFromRuleStringPolylist(Polylist rulePL){
  1015.  
  1016.  
  1017. Polylist rhythmPL = getRhythmPolylistFromRuleStringPL(rulePL);
  1018.  
  1019. String visualization = makeRealMelodyFromRhythmPolylist(rhythmPL);
  1020.  
  1021. return visualization;
  1022.  
  1023. }
  1024.  
  1025. private Polylist getRhythmPolylistFromRuleStringPL(Polylist rulePL){
  1026. // System.out.println("\nrulePL: " + rulePL);
  1027. // System.out.println("\nrulePL first: " + rulePL.first());
  1028. // System.out.println("rulePL second is: " + rulePL.second());
  1029. // System.out.println("is rulePL second a polylist?? " + (rulePL.second() instanceof Polylist));
  1030. // System.out.println("rulePL third(): " + rulePL.third());
  1031. Polylist Xnotation = (Polylist) rulePL.third();
  1032. //remove Xnotation tag
  1033. Xnotation = Xnotation.rest();
  1034. String relativePitchString = Xnotation.toString();
  1035. //System.out.println("relativePitchSrt is: " + relativePitchString);
  1036.  
  1037. Polylist rhythmPL = getRelativePitchPolylist(relativePitchString);
  1038. return rhythmPL;
  1039. }
  1040.  
  1041. public Polylist getRelativePitchPolylist(String relativePitchMelody){
  1042. String[] part = relativePitchMelody.split("\\(|\\)");
  1043.  
  1044. Polylist relativePL = Polylist.list("rhythm");
  1045. for (String s: part){
  1046. s = s.trim();//remove trailing and leading whitespace
  1047. if(s.length() == 0){continue;}//skip empty strings
  1048. if(s.charAt(0) == 'R'){
  1049. Polylist note = DataPoint.getNotePolylistWLeadingR(s);
  1050.  
  1051. relativePL = relativePL.addToEnd(note);
  1052. }else if(s.charAt(0) == 'X'){
  1053. Polylist note = DataPoint.getNotePolylistWLeadingX(s);
  1054. relativePL = relativePL.addToEnd(note);
  1055. }
  1056. }
  1057.  
  1058. return relativePL;
  1059. }
  1060.  
  1061.  
  1062. // Variables declaration - do not modify
  1063. // End of variables declaration
  1064. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement