]> 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;
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();
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() {
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                 y = insets.top + Math.round(mn.getTick() / ticksPerSixteenth) * NOTE_HEIGHT;
136                 height = (mn.getDuration() / ticksPerSixteenth) * NOTE_HEIGHT;
137                 if (height == 0) height = NOTE_HEIGHT;
138                 r = new Rectangle(x, y, NOTE_WIDTH, height);
139
140                 // Places the element in the appropriate place.
141                 while(isOccupied(r)) r.translate(NOTE_WIDTH, 0);
142                 elem.setBounds(r);
143                 coords.add(r);
144                 if (viewLength < (y + height)){
145                         viewLength = y + height;
146                         if(old)setPreferredSize(new Dimension(VIEW_WIDTH, viewLength + extraHeight));
147                 }
148                 if (old) {
149                         validate();
150                         repaint();
151                 }
152         }
153
154         /** 
155          * Returns the track of this view.
156          * @return the track of this view
157          */
158         public Track getTrack() {
159                 return track;
160         }
161
162         /** 
163          * Returns the title of this view.
164          * @return the title of this view
165          */
166         public MooTrackTitle getTitle() {
167                 return title;
168         }
169
170         /**
171          * Checks if the element can be fully drawn as this position without inteferring with other elements.
172          * @return true if the position is occupied.
173          */
174         private boolean isOccupied(Rectangle r) {
175                 Iterator it = coords.iterator();
176                 while (it.hasNext()) {
177                         if(r.intersects((Rectangle)it.next())) return true;
178                 }
179                 return false;
180         }
181         
182         /** 
183          * Adds the given note to the current track, and visualises it.
184          * @param mn    the note to add
185          */
186         public void addNote(MooNote mn) {
187                 mn.addTo(track);
188                 MooNoteElement elem = new MooNoteElement(this, mn);
189                 add(elem);
190                 layoutElement(elem, false);
191                 setPreferredSize(new Dimension(VIEW_WIDTH, viewLength + extraHeight));
192                 Moosique.setEdited();
193                 validate();
194                 repaint();
195         }
196
197         /**
198          * Adds a standard note to this track.
199          */
200         private void addStandardNote() {
201                 int row = (popupY - insets.top) / NOTE_HEIGHT;
202                 long timestamp = (long)(ticksPerSixteenth * row);
203                 addNote(new MooNote(title.getChannel(), 60, 100, timestamp, Moosique.getSequence().getResolution() / 4));
204         }
205
206         /** 
207          * Removes the given note element from the view and its note from the current track.
208          * @param elem  the note element to remove
209          */
210         public void removeNote(MooNoteElement elem) {
211                 elem.getNote().removeFrom(track);
212                 remove(elem);
213                 Rectangle r = new Rectangle();
214                 r = elem.getBounds(r);
215                 coords.remove(r);
216                 Moosique.setEdited();
217                 validate();
218                 repaint();
219         }
220
221         /**
222          * Selects the given note
223          * @param the note to select
224          */
225         public void selectNote(MooNoteElement elem) {
226                 selection.add(elem);
227         }
228
229         /**
230          * Deselects the given note
231          * @param the note to deselect
232          */
233         public void deselectNote(MooNoteElement elem) {
234                 selection.remove(elem);
235         }
236
237         /**
238          * Deselects all notes.
239          */
240         public void deselectAllNotes() {
241                 Iterator it = selection.iterator();
242                 while(it.hasNext()) {
243                         ((MooNoteElement)it.next()).deselect();
244                 }
245                 selection.clear();
246         }
247
248         /**
249          * Determines if the given MooNoteElement is the only one in the track view that is selected.
250          * @return if the given element is the only selected one
251          */
252         public boolean isTheOnlySelected(MooNoteElement elem) {
253                 Iterator it = selection.iterator();
254                 while(it.hasNext()) {
255                         if (!it.next().equals(elem)) return false;
256                 }
257                 return true;
258         }
259
260         /**
261          * Copies the current selection.
262          */
263         public void copySelectedNotes() {
264                 ArrayList copyBuffer = new ArrayList(selection.size());
265                 Iterator it = selection.iterator();
266                 while(it.hasNext()) {
267                         copyBuffer.add(((MooNoteElement)it.next()).getNote().clone());
268                 }
269                 Collections.sort(copyBuffer);
270                 Moosique.setCopyBuffer(copyBuffer);
271         }
272
273         /**
274          * Cuts the current selection.
275          */
276         public void cutSelectedNotes() {
277                 copySelectedNotes();
278                 removeSelectedNotes();
279         }
280
281         /**
282          * Pastes the current copy buffer at the given timestamp.
283          */
284         public void pasteCopiedNotes() {
285                 int row = (popupY - insets.top) / NOTE_HEIGHT;
286                 long timestamp = (long)(ticksPerSixteenth * row);
287                 ArrayList copyBuffer = Moosique.getCopyBuffer();
288                 if (copyBuffer.size() > 0) {
289                         long startTime = ((MooNote)copyBuffer.get(0)).getTick();
290                         Iterator it = copyBuffer.iterator();
291                         while(it.hasNext()) {
292                                 MooNote mn = (MooNote)((MooNote)it.next()).clone();
293                                 mn.setTick(mn.getTick() - startTime + timestamp);
294                                 mn.setChannel(title.getChannel());
295                                 addNote(mn);
296                         }
297                 }
298         }
299
300         /**
301          * Removes the current selection.
302          */
303         public void removeSelectedNotes() {
304                 Iterator it = selection.iterator();
305                 while(it.hasNext()) {
306                         removeNote((MooNoteElement)it.next());
307                 }
308                 selection.clear();
309         }
310
311         /**
312          * Transposes all selected notes the given number of halftones.
313          */
314         private void transposeSelectedNotes(int halftones) {
315                 Iterator it = selection.iterator();
316                 while(it.hasNext()) {
317                         MooNoteElement elem = (MooNoteElement)it.next();
318                         elem.transpose(halftones);
319                 }
320         }
321
322         /**
323          * Moves the current selection the given number of ticks.
324          * @param ticks         the number of ticks to move the selection.
325          */
326         public void moveSelectedNotes(int ticks) {
327                 if (ticks < 0) {
328                         // If the selection should be moved upwards, traverses the list in the natural order.
329                         Iterator it = selection.iterator();
330                         while(it.hasNext()) {
331                                 MooNoteElement elem = (MooNoteElement)it.next();
332                                 elem.getNote().setTick(elem.getNote().getTick() + ticks);
333                                 layoutElement(elem, true);
334                         }
335                 } else {
336                         // If the selection should be moved downwards, traverses the list in the opposite order.
337                         ArrayList selectedList = new ArrayList(selection);
338                         ListIterator it = selectedList.listIterator(selectedList.size());
339                         while(it.hasPrevious()) {
340                                 MooNoteElement elem = (MooNoteElement)it.previous();
341                                 elem.getNote().setTick(elem.getNote().getTick() + ticks);
342                                 layoutElement(elem, true);
343                         }
344                 }
345         }
346
347         /**
348          * Moves the current selection, depending on the given delta y.
349          * @param y     the number of pixels the selection is moved.
350          */
351         public void maybeMoveSelectedNotes(int y) {
352                 moveSelectedNotes(ticksPerSixteenth * (y / NOTE_HEIGHT));
353         }
354
355         /**
356          * Enables keyboard recording.
357          */
358         public void enableKeyboardRecording() {
359                 keyboard.recordEnable();
360         }
361
362         /**
363          * Disables keyboard recording.
364          */
365         public void disableKeyboardRecording() {
366                 keyboard.recordDisable();
367         }
368
369         /**
370          * Adds a menu item with the given command to the given popup menu.
371          */
372         private JMenuItem addMenuItem(JPopupMenu menu, String command) {
373                 JMenuItem item = new JMenuItem(command);
374                 item.addActionListener(new PopupListener());
375                 menu.add(item);
376                 return item;
377         }
378
379         /**
380          * Adds a menu item with the given command to the given menu.
381          */
382         private JMenuItem addMenuItem(JMenu menu, String command) {
383                 JMenuItem item = new JMenuItem(command);
384                 item.addActionListener(new PopupListener());
385                 menu.add(item);
386                 return item;
387         }
388
389         /**
390          * Creates a transpose sub menu with the given title in the given popup menu,
391          * inserting the items into the given array.
392          */
393         private JMenu createTransposeMenu(JPopupMenu menu, JMenuItem[] items, String title) {
394                 JMenu trans = new JMenu("Transpose " + title);
395                 menu.add(trans);
396                 items[0] = addMenuItem(trans, "One octave");
397                 for (int i = 1; i < 12; i++) {
398                         items[i] = addMenuItem(trans, (i) + " halftones");
399                 }
400                 return trans;
401         }
402
403         /**
404          * Shows a popup-menu with options for the current selection of note elements.
405          * @param c     the component over which to display the menu
406          * @param x     the x-coordinate in which to display the menu
407          * @param y     the y-coordinate in which to display the menu
408          */
409         public void showSelectionPopup(Component c, int x, int y) {
410                 selPopup.show(c, x, y);
411         }
412
413         /**
414          * Draws the grid that is on the background.
415          * @param g The Graphics object used to draw the grid.
416          */
417         public void paintComponent(Graphics g) {
418                 super.paintComponent(g);
419                 Graphics2D g2 = (Graphics2D)g;
420                 for (int c = 0; c < viewLength || c < getHeight(); c += NOTE_HEIGHT) {
421                         for (int r = 0; r < (10 * NOTE_WIDTH); r += NOTE_WIDTH) {
422                                 box = new Rectangle(r, c, NOTE_WIDTH, NOTE_HEIGHT);
423                                 g2.setColor(Color.gray);
424                                 g2.draw(box);
425                         }
426                 }
427         }
428         
429         /**
430          * Returns whether the left mouse button is currently pressed or not.
431          * @return true if the left mosue button is currently pressed
432          */
433         public boolean isLeftMouseButtonPressed() {
434                 return leftMouseButtonPressed;
435         }
436
437         /**
438          * The adapter used to listen on mouse actions
439          */
440         class MAdapter extends MouseAdapter {
441
442                 /**
443                  * Deselects all note on click, adds a standard note on double click.
444                  */
445                 public void mouseClicked(MouseEvent e) {
446                         if (SwingUtilities.isLeftMouseButton(e)) {
447                                 deselectAllNotes();
448                                 if (e.getClickCount() == 2) {
449                                         popupY = e.getY();
450                                         addStandardNote();
451                                 }
452                         }
453                 }
454         
455                 public void mousePressed(MouseEvent e) {
456                         if (SwingUtilities.isLeftMouseButton(e)) leftMouseButtonPressed = true;
457                         maybeShowPopup(e);
458                 }
459
460                 public void mouseReleased(MouseEvent e) {
461                         if (SwingUtilities.isLeftMouseButton(e)) leftMouseButtonPressed = false;
462                         maybeShowPopup(e);
463                 }
464
465                 /**
466                  * Shows the menu if an OS-specific popup-trigger was activated.
467                  */
468                 private void maybeShowPopup(MouseEvent e) {
469                         if (e.isPopupTrigger()) {
470                                 popupY = e.getY();
471                                 popup.show(e.getComponent(), e.getX(), e.getY());
472                         }
473                 }
474
475                 /**
476                  * Grabs the focus when the mouse has entered.
477                  */
478                 public void mouseEntered(MouseEvent e) {
479                         Moosique.setActiveChannel(title.getChannel());
480                         grabFocus();
481                 }
482         }
483
484         /**
485          * Takes the appropriate action when a user selects an item on the popup menu.
486          */
487         class PopupListener implements ActionListener {
488                 public void actionPerformed(ActionEvent e) {
489                         Object source = e.getSource();
490                         // Handling panel popup actions.
491                         if (source == popupAdd) {
492                                 addStandardNote();
493                         } else if (source == popupPaste) {
494                                 pasteCopiedNotes();
495                         // Handling selection popup actions.
496                         } else if (source == selPopupCopy) {
497                                 copySelectedNotes();
498                         } else if (source == selPopupCut) {
499                                 cutSelectedNotes();
500                         } else if (source == selPopupRemove) {
501                                 removeSelectedNotes();
502                         } else if (source == selPopupTranspUpItems[0]) {
503                                 transposeSelectedNotes(12);
504                         } else if (source == selPopupTranspDownItems[0]) {
505                                 transposeSelectedNotes(-12);
506                         } else {
507                                 for (int i = 1; i < 12; i++) {
508                                         if (source == selPopupTranspUpItems[i]) transposeSelectedNotes(i);
509                                         else if (source == selPopupTranspDownItems[i]) transposeSelectedNotes(-i);
510                                 }
511                         }
512                 }
513         }
514 }