]> ruin.nu Git - moosique.git/blob - MooTrackView.java
no message
[moosique.git] / MooTrackView.java
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import javax.sound.midi.*;
5 import java.util.*;
6
7 /**
8  * Graphical representation of a MIDI track.
9  * 
10  * @author  Andersson , Andreen, Lanneskog, Pehrson
11  * @version 1
12  */
13
14 public class MooTrackView extends JPanel {
15
16         private Track track;
17         private MooTrackTitle title;
18         private MooKeyboard keyboard;
19
20         private JPopupMenu popup, selPopup;
21         private JMenu selPopupTranspUp, selPopupTranspDown;
22         private JMenuItem popupAdd, popupPaste;
23         private JMenuItem selPopupCopy, selPopupCut, selPopupRemove;
24         private JMenuItem[] selPopupTranspUpItems, selPopupTranspDownItems;
25
26         private ArrayList coords; 
27         private TreeSet selection;
28         private Insets insets;
29         private Rectangle box;
30         private int ticksPerSixteenth, popupY = 0;
31         private boolean leftMouseButtonPressed = false, quantizeRecording = false;
32         protected static int viewLength = 0;
33         protected static int extraHeight = 0;
34         public static final int NOTE_HEIGHT = 10, NOTE_WIDTH = 40, VIEW_WIDTH = 200;
35
36         /**
37          * Creates the trackview.
38          * @param track The track it represents graphically and operates on.
39          * @param title The object that is used to manipulate instrument, channel, solo, mute.
40          */
41         public MooTrackView (Track track, MooTrackTitle title) {
42                 super(true);
43
44                 // Defines instance variables
45                 this.track = track;
46                 this.title = title;
47                 insets = getInsets();
48
49                 // Configures panel
50                 setBackground(Color.white);
51                 setBorder(BorderFactory.createLineBorder(Color.black));
52                 setLayout(null);
53                 setPreferredSize(new Dimension(VIEW_WIDTH, 140 * NOTE_HEIGHT));
54
55                 placeNoteElements(false);
56
57                 // Creates panel pop-up menu.
58                 popup = new JPopupMenu();
59                 popupAdd = addMenuItem(popup, "Add note...");
60                 popupPaste = addMenuItem(popup, "Paste");
61
62                 // Creates selection pop-up menu.
63                 selPopup = new JPopupMenu();
64                 selPopupCopy = addMenuItem(selPopup, "Copy selection");
65                 selPopupCut = addMenuItem(selPopup, "Cut selection");
66                 selPopupRemove = addMenuItem(selPopup, "Remove selection");
67                 selPopupTranspUpItems = new JMenuItem[12];
68                 selPopupTranspDownItems = new JMenuItem[12];
69                 selPopupTranspUp = createTransposeMenu(selPopup, selPopupTranspUpItems, "selection up");
70                 selPopupTranspDown = createTransposeMenu(selPopup, selPopupTranspDownItems, "selection down");
71
72                 // Adds listeners for popup menu and keyboard synthesizer.
73                 addMouseListener(new MAdapter());
74                 keyboard = new MooKeyboard(title);
75                 addKeyListener(keyboard);
76         }
77
78         /**
79          * Creates note elements for all MooNotes in the track, and places them in the appropriate place.
80          */
81         public void placeNoteElements(boolean quantize) {
82                 // Converts the track.
83                 Moosique.convertTrack(track);
84
85                 // Empties the container
86                 removeAll();
87                 coords = new ArrayList(track.size() / 2);
88                 selection = new TreeSet();
89
90                 // Creates temporary variables
91                 MidiEvent note;
92                 MooNoteElement elem;
93                 extraHeight = Toolkit.getDefaultToolkit().getScreenSize().height - 150;
94
95                 // Places note elements
96                 for (int i = 0; i < track.size(); i++) {
97                         note = track.get(i);
98                         if (note instanceof MooNote) {
99                                 // Adds the note element to the note area and moves it to the appropriate place.
100                                 MooNote mn = (MooNote)note;
101                                 elem = new MooNoteElement(this, mn);
102                                 add(elem);
103                                 layoutElement(elem, false);
104                         }
105                         setPreferredSize(new Dimension(VIEW_WIDTH, viewLength + extraHeight));
106                 }
107         }       
108
109         /**
110          * Layouts the element to the right place.
111          * @param elem  the element that will be layouted.
112          * @param old   If true, this method will remove the old layout and set the new preferredSize for the trackview.
113          */
114         public void layoutElement(MooNoteElement elem, boolean old){
115                 // If the element is currently in the view, removes its coordinates from the list.
116                 Rectangle r = new Rectangle();
117                 if (old){
118                         r = elem.getBounds(r);
119                         for (Iterator i = coords.iterator(); i.hasNext();){
120                                 Object ob = i.next();
121                                 if (r.equals(ob)){
122                                         coords.remove(ob);
123                                         break;
124                                 }
125                         }
126                 }
127
128                 // Creates temporary variables.
129                 ticksPerSixteenth = Moosique.getSequence().getResolution() / 4;
130                 MooNote mn = elem.getNote();
131                 int x, y, height;
132
133                 // Calculates coordinates.
134                 x = insets.left;
135                 if (quantizeRecording) {
136                 
137                 } else {
138                         y = insets.top + (int)((mn.getTick() * NOTE_HEIGHT) / ticksPerSixteenth);
139                         height = (mn.getDuration() * NOTE_HEIGHT) / ticksPerSixteenth;
140                 }
141                 if (height == 0) height = NOTE_HEIGHT;
142                 r = new Rectangle(x, y, NOTE_WIDTH, height);
143
144                 // Places the element in the appropriate place.
145                 while(isOccupied(r)) r.translate(NOTE_WIDTH, 0);
146                 elem.setBounds(r);
147                 coords.add(r);
148                 if (viewLength < (y + height)){
149                         viewLength = y + height;
150                         if(old)setPreferredSize(new Dimension(VIEW_WIDTH, viewLength + extraHeight));
151                 }
152                 if (old) {
153                         validate();
154                         repaint();
155                 }
156         }
157
158         /** 
159          * Returns the track of this view.
160          * @return the track of this view
161          */
162         public Track getTrack() {
163                 return track;
164         }
165
166         /** 
167          * Returns the title of this view.
168          * @return the title of this view
169          */
170         public MooTrackTitle getTitle() {
171                 return title;
172         }
173
174         /**
175          * Checks if the element can be fully drawn as this position without inteferring with other elements.
176          * @return true if the position is occupied.
177          */
178         private boolean isOccupied(Rectangle r) {
179                 Iterator it = coords.iterator();
180                 while (it.hasNext()) {
181                         if(r.intersects((Rectangle)it.next())) return true;
182                 }
183                 return false;
184         }
185         
186         /** 
187          * Adds the given note to the current track, and visualises it.
188          * @param mn    the note to add
189          */
190         public void addNote(MooNote mn) {
191                 mn.addTo(track);
192                 MooNoteElement elem = new MooNoteElement(this, mn);
193                 add(elem);
194                 layoutElement(elem, false);
195                 setPreferredSize(new Dimension(VIEW_WIDTH, viewLength + extraHeight));
196                 Moosique.setEdited();
197                 validate();
198                 repaint();
199         }
200
201         /**
202          * Adds a standard note to this track.
203          */
204         private void addStandardNote() {
205                 int row = (popupY - insets.top) / NOTE_HEIGHT;
206                 long timestamp = (long)(ticksPerSixteenth * row);
207                 addNote(new MooNote(title.getChannel(), 60, 100, timestamp, Moosique.getSequence().getResolution() / 4));
208         }
209
210         /** 
211          * Removes the given note element from the view and its note from the current track.
212          * @param elem  the note element to remove
213          */
214         public void removeNote(MooNoteElement elem) {
215                 elem.getNote().removeFrom(track);
216                 remove(elem);
217                 Rectangle r = new Rectangle();
218                 r = elem.getBounds(r);
219                 coords.remove(r);
220                 Moosique.setEdited();
221                 validate();
222                 repaint();
223         }
224
225         /**
226          * Selects the given note
227          * @param the note to select
228          */
229         public void selectNote(MooNoteElement elem) {
230                 selection.add(elem);
231         }
232
233         /**
234          * Deselects the given note
235          * @param the note to deselect
236          */
237         public void deselectNote(MooNoteElement elem) {
238                 selection.remove(elem);
239         }
240
241         /**
242          * Deselects all notes.
243          */
244         public void deselectAllNotes() {
245                 Iterator it = selection.iterator();
246                 while(it.hasNext()) {
247                         ((MooNoteElement)it.next()).deselect();
248                 }
249                 selection.clear();
250         }
251
252         /**
253          * Determines if the given MooNoteElement is the only one in the track view that is selected.
254          * @return if the given element is the only selected one
255          */
256         public boolean isTheOnlySelected(MooNoteElement elem) {
257                 Iterator it = selection.iterator();
258                 while(it.hasNext()) {
259                         if (!it.next().equals(elem)) return false;
260                 }
261                 return true;
262         }
263
264         /**
265          * Copies the current selection.
266          */
267         public void copySelectedNotes() {
268                 ArrayList copyBuffer = new ArrayList(selection.size());
269                 Iterator it = selection.iterator();
270                 while(it.hasNext()) {
271                         copyBuffer.add(((MooNoteElement)it.next()).getNote().clone());
272                 }
273                 Collections.sort(copyBuffer);
274                 Moosique.setCopyBuffer(copyBuffer);
275         }
276
277         /**
278          * Cuts the current selection.
279          */
280         public void cutSelectedNotes() {
281                 copySelectedNotes();
282                 removeSelectedNotes();
283         }
284
285         /**
286          * Pastes the current copy buffer at the given timestamp.
287          */
288         public void pasteCopiedNotes() {
289                 int row = (popupY - insets.top) / NOTE_HEIGHT;
290                 long timestamp = (long)(ticksPerSixteenth * row);
291                 ArrayList copyBuffer = Moosique.getCopyBuffer();
292                 if (copyBuffer.size() > 0) {
293                         long startTime = ((MooNote)copyBuffer.get(0)).getTick();
294                         Iterator it = copyBuffer.iterator();
295                         while(it.hasNext()) {
296                                 MooNote mn = (MooNote)((MooNote)it.next()).clone();
297                                 mn.setTick(mn.getTick() - startTime + timestamp);
298                                 mn.setChannel(title.getChannel());
299                                 addNote(mn);
300                         }
301                 }
302         }
303
304         /**
305          * Removes the current selection.
306          */
307         public void removeSelectedNotes() {
308                 Iterator it = selection.iterator();
309                 while(it.hasNext()) {
310                         removeNote((MooNoteElement)it.next());
311                 }
312                 selection.clear();
313         }
314
315         /**
316          * Transposes all selected notes the given number of halftones.
317          */
318         private void transposeSelectedNotes(int halftones) {
319                 Iterator it = selection.iterator();
320                 while(it.hasNext()) {
321                         MooNoteElement elem = (MooNoteElement)it.next();
322                         elem.transpose(halftones);
323                 }
324         }
325
326         /**
327          * Moves the current selection the given number of ticks.
328          * @param ticks         the number of ticks to move the selection.
329          */
330         public void moveSelectedNotes(int ticks) {
331                 if (ticks < 0) {
332                         // If the selection should be moved upwards, traverses the list in the natural order.
333                         Iterator it = selection.iterator();
334                         while(it.hasNext()) {
335                                 MooNoteElement elem = (MooNoteElement)it.next();
336                                 elem.getNote().setTick(elem.getNote().getTick() + ticks);
337                                 layoutElement(elem, true);
338                         }
339                 } else {
340                         // If the selection should be moved downwards, traverses the list in the opposite order.
341                         ArrayList selectedList = new ArrayList(selection);
342                         ListIterator it = selectedList.listIterator(selectedList.size());
343                         while(it.hasPrevious()) {
344                                 MooNoteElement elem = (MooNoteElement)it.previous();
345                                 elem.getNote().setTick(elem.getNote().getTick() + ticks);
346                                 layoutElement(elem, true);
347                         }
348                 }
349         }
350
351         /**
352          * Moves the current selection, depending on the given delta y.
353          * @param y     the number of pixels the selection is moved.
354          */
355         public void maybeMoveSelectedNotes(int y) {
356                 moveSelectedNotes(ticksPerSixteenth * (y / NOTE_HEIGHT));
357         }
358
359         /**
360          * Enables keyboard recording.
361          */
362         public void enableKeyboardRecording() {
363                 keyboard.recordEnable();
364         }
365
366         /**
367          * Disables keyboard recording.
368          */
369         public void disableKeyboardRecording() {
370                 keyboard.recordDisable();
371         }
372
373         /**
374          * Adds a menu item with the given command to the given popup menu.
375          */
376         private JMenuItem addMenuItem(JPopupMenu menu, String command) {
377                 JMenuItem item = new JMenuItem(command);
378                 item.addActionListener(new PopupListener());
379                 menu.add(item);
380                 return item;
381         }
382
383         /**
384          * Adds a menu item with the given command to the given menu.
385          */
386         private JMenuItem addMenuItem(JMenu menu, String command) {
387                 JMenuItem item = new JMenuItem(command);
388                 item.addActionListener(new PopupListener());
389                 menu.add(item);
390                 return item;
391         }
392
393         /**
394          * Creates a transpose sub menu with the given title in the given popup menu,
395          * inserting the items into the given array.
396          */
397         private JMenu createTransposeMenu(JPopupMenu menu, JMenuItem[] items, String title) {
398                 JMenu trans = new JMenu("Transpose " + title);
399                 menu.add(trans);
400                 items[0] = addMenuItem(trans, "One octave");
401                 for (int i = 1; i < 12; i++) {
402                         items[i] = addMenuItem(trans, (i) + " halftones");
403                 }
404                 return trans;
405         }
406
407         /**
408          * Shows a popup-menu with options for the current selection of note elements.
409          * @param c     the component over which to display the menu
410          * @param x     the x-coordinate in which to display the menu
411          * @param y     the y-coordinate in which to display the menu
412          */
413         public void showSelectionPopup(Component c, int x, int y) {
414                 selPopup.show(c, x, y);
415         }
416
417         /**
418          * Draws the grid that is on the background.
419          * @param g The Graphics object used to draw the grid.
420          */
421         public void paintComponent(Graphics g) {
422                 super.paintComponent(g);
423                 Graphics2D g2 = (Graphics2D)g;
424                 for (int c = 0; c < viewLength || c < getHeight(); c += NOTE_HEIGHT) {
425                         for (int r = 0; r < (10 * NOTE_WIDTH); r += NOTE_WIDTH) {
426                                 box = new Rectangle(r, c, NOTE_WIDTH, NOTE_HEIGHT);
427                                 g2.setColor(Color.gray);
428                                 g2.draw(box);
429                         }
430                 }
431         }
432         
433         /**
434          * Returns whether the left mouse button is currently pressed or not.
435          * @return true if the left mosue button is currently pressed
436          */
437         public boolean isLeftMouseButtonPressed() {
438                 return leftMouseButtonPressed;
439         }
440
441         /**
442          * The adapter used to listen on mouse actions
443          */
444         class MAdapter extends MouseAdapter {
445
446                 /**
447                  * Deselects all note on click, adds a standard note on double click.
448                  */
449                 public void mouseClicked(MouseEvent e) {
450                         if (SwingUtilities.isLeftMouseButton(e)) {
451                                 deselectAllNotes();
452                                 if (e.getClickCount() == 2) {
453                                         popupY = e.getY();
454                                         addStandardNote();
455                                 }
456                         }
457                 }
458         
459                 public void mousePressed(MouseEvent e) {
460                         if (SwingUtilities.isLeftMouseButton(e)) leftMouseButtonPressed = true;
461                         maybeShowPopup(e);
462                 }
463
464                 public void mouseReleased(MouseEvent e) {
465                         if (SwingUtilities.isLeftMouseButton(e)) leftMouseButtonPressed = false;
466                         maybeShowPopup(e);
467                 }
468
469                 /**
470                  * Shows the menu if an OS-specific popup-trigger was activated.
471                  */
472                 private void maybeShowPopup(MouseEvent e) {
473                         if (e.isPopupTrigger()) {
474                                 popupY = e.getY();
475                                 popup.show(e.getComponent(), e.getX(), e.getY());
476                         }
477                 }
478
479                 /**
480                  * Grabs the focus when the mouse has entered.
481                  */
482                 public void mouseEntered(MouseEvent e) {
483                         Moosique.setActiveChannel(title.getChannel());
484                         grabFocus();
485                 }
486         }
487
488         /**
489          * Takes the appropriate action when a user selects an item on the popup menu.
490          */
491         class PopupListener implements ActionListener {
492                 public void actionPerformed(ActionEvent e) {
493                         Object source = e.getSource();
494                         // Handling panel popup actions.
495                         if (source == popupAdd) {
496                                 addStandardNote();
497                         } else if (source == popupPaste) {
498                                 pasteCopiedNotes();
499                         // Handling selection popup actions.
500                         } else if (source == selPopupCopy) {
501                                 copySelectedNotes();
502                         } else if (source == selPopupCut) {
503                                 cutSelectedNotes();
504                         } else if (source == selPopupRemove) {
505                                 removeSelectedNotes();
506                         } else if (source == selPopupTranspUpItems[0]) {
507                                 transposeSelectedNotes(12);
508                         } else if (source == selPopupTranspDownItems[0]) {
509                                 transposeSelectedNotes(-12);
510                         } else {
511                                 for (int i = 1; i < 12; i++) {
512                                         if (source == selPopupTranspUpItems[i]) transposeSelectedNotes(i);
513                                         else if (source == selPopupTranspDownItems[i]) transposeSelectedNotes(-i);
514                                 }
515                         }
516                 }
517         }
518 }